|
||
|
Inner classes: anonymous classes The Anonymous program
The Anonymous program illustrates the use of anonymous inner classes. It creates a window program with a moving button. The
Anonymous() constructor uses an anonymous inner class to create an object that implements the ActionListener
interface to handle the clicking of the button. This object provides an implementation of the actionPerformed() method. Note
that the button variable is declared as final. The Anonymous() constructor also uses an anonymous inner
class that extends the WindowAdapter class to handle the closing of the application window.
|
||
The Anonymous program import java.awt.*; import java.awt.event.*; class Anonymous extends Frame { public static void main(String[] args) { new Anonymous(); } Anonymous() { setLayout(null); final Button button = new Button("Click me!"); button.setBounds(100,100,100,100); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (button.getLocation().x == 100) button.setBounds(200,200,100,100); else button.setBounds(100,100,100,100); } }); add(button); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(400,400); show(); } } |
||
|
|
||