Page 694 - Introduction to Programming with Java: A Problem Solving Approach
P. 694

                660 Chapter 16 GUI Programming Basics
 }
// end class GreetingAnonymous
//*********************************************************
// Create components and add them to window.
private void createContents()
{
JLabel namePrompt = new JLabel("What's your name?");
nameBox = new JTextField(15);
greeting = new JLabel();
add(namePrompt);
add(nameBox);
add(greeting);
nameBox.addActionListener(
// anonymous inner class for event handling
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
String message; // the personalized greeting
message = "Glad to meet you, " + nameBox.getText();
nameBox.setText("");
greeting.setText(message);
// end actionPerformed
     Apago PDF Enhancer
} // end anonymous inner class
); // end addActionListener call
// end createContents
//*********************************************************
}
public static void main(String[] args)
{
new GreetingAnonymous();
} // end main
Figure 16.6b GreetingAnonymous program that has an anonymous inner class—part B
In the Greeting program, we implemented a listener class named Listener, using this code:
private class Listener implements ActionListener
{
That code is omitted in the GreetingAnonymous program—there’s no class named Listener. But we still need a listener object so that the text box’s enter event is detected and acted upon. This time, instead of de- claring a listener class with a name (e.g., Listener), we implement a listener class anonymously (without a name).
We’ve discussed anonymous objects previously. That’s where you instantiate an object without storing its reference in a variable. In our previous Greeting program, we instantiated an anonymous Listener object with this line:
nameBox.addActionListener(new Listener());

























































   692   693   694   695   696