In this example you will learn how to use anonymous inner class listeners.
We have also given the complete code example so that you can try and learn the concepts.
There is no need to define a named class simply to add a listener object to a button.
Java has a somewhat obscure syntax for creating an anonymous innner class listener that implements an interface.
There is no need to memorize the syntax; just copy and paste it each time. For example,
class myPanel extends JPanel {
. . .
public MyPanel() {
. . . //in the constructor
JButton b1 = new JButton("Hello");
b1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something for button b1
}
}
);
The above example creates a subclass of Object that
implements the ActionListener interface.
The compiler creates names for anonymous classes. The JDK
typically uses the enclosing class name followed by $ followed
by a number, eg, you may see a MyPanel$1.class
file generated by the compiler.