Java Reference
In-Depth Information
That said, whichever listener you're using, you should still consider a few additional aspects. The
first one relates to the event source—the component sending the event to the listeners. Earlier on,
you read that in some cases you might want to determine exactly which button was clicked. For
example, take the following base scenario:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class ActionListenerExample extends JFrame implements ActionListener {
public ActionListenerExample() {
super();
this.setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn1 = new JButton("Click Me!");
JButton btn2 = new JButton("No, click me!");
btn1.addActionListener(this);
btn2.addActionListener(this);
getContentPane().add(btn1);
getContentPane().add(btn2);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ev) {
JOptionPane.showMessageDialog(
null,
"You clicked a button!",
"Aw yeah!",
JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ActionListenerExample();
}
});
}
}
This class is comparable to the earlier example and acts as both a container and an action listener for
two buttons. Now say you want to show a different message depending on which button was clicked.
The first way to do this is by changing the actionPerformed method as follows:
@Override
public void actionPerformed(ActionEvent ev) {
Search WWH ::




Custom Search