Java Reference
In-Depth Information
The main benefit of this technique is that it is easy and simple, so it works well for simple com-
ponents. The downside it that it leads quickly to messy‐looking code, does not allow the same
listener to be reused in multiple components, and will sometimes require you to do some vari-
able hocus‐pocus to access them in the inner class (remember the self variable from the Try It
Out).
The second way will make the container component itself the event listener. This is helpful when you
have multiple components to listen to and you already have a custom class for your container. In this
case, you'll see the pattern class Name extends JContainerName implements ListenerName
appearing, like in this example:
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();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Click Me!");
// The JFrame is now also the listener object
btn.addActionListener(this);
this.add(btn);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(
null,
"You clicked me, nice!",
"Aw yeah!",
JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ActionListenerExample();
}
});
}
}
Search WWH ::




Custom Search