I write a program in java and used a several components that takes action(actionListener) in my program.
I want to know when any action happened by this component. For example when I clicked the button or a menu item , call a method.
public class ButtonFrame extends JFrame
{
private JButton plainJButton; // button with just text
private JButton fancyJButton; // button with icons
public ButtonFrame()
{
super( "Testing Buttons" );
setLayout( new FlowLayout() ); // set frame layout
plainJButton = new JButton( "Plain Button" );
add( plainJButton );
fancyJButton = new JButton( "Fancy Button");
add( fancyJButton );
// create new ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
fancyJButton.addActionListener( handler );
plainJButton.addActionListener( handler );
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( ButtonFrame.this, String.format(
"You pressed: %s", event.getActionCommand() ) );
}
}
}
Use
event.getSource()to differentiate between registered components.Example –