Home Java Java-tips GUI Events Anonymous Listeners

Ask Questions?

View Latest Questions

Advertisement


 
 

Anonymous Listeners
Posted on: July 26, 2006 at 12:00 AM
You will learn the syntax for creating an anonymous innner class listener .

Java Notes

Anonymous Listeners

 

Using anonymous inner class listeners - a common idiom

 

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
                }
            }
        );

Creates a class

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.

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com