Java Reference
In-Depth Information
16.9
If class A is an inner class in class B , what is the .class file for A ? If class B contains
two anonymous inner classes, what are the .class file names for these two classes?
Check
Point
16.10
What is wrong in the following code?
import java.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
public Test() {
JButton jbtOK = new JButton( "OK" );
add(jbtOK);
public class Test extends JFrame {
public Test() {
JButton jbtOK = new JButton( "OK" );
add(jbtOK);
jbtOK.addActionListener(
new ActionListener() {
public void actionPerformed
(ActionEvent e) {
System.out.println
(jbtOK.getActionCommand());
}
private class Listener
implements ActionListener {
public void actionPerform
(ActionEvent e) {
System.out.println
(jbtOK.getActionCommand());
}
} // Something missing here
}
}
}
/** Main method omitted */
/** Main method omitted */
}
}
(a)
(b)
16.11
What is the difference between the setSize(width, height) method and the
pack() method in JFrame ?
16.6 Alternative Ways of Defining Listener Classes
Using an inner class or an anonymous inner class is preferred for defining listener
classes.
Key
Point
There are many other ways to define the listener classes. For example, you can rewrite Listing
16.4 by creating just one listener, register the listener with the buttons, and let the listener
detect the event source—that is, which button fires the event—as shown in Listing 16.5.
L ISTING 16.5 DetectSourceDemo.java
1 import javax.swing.*;
2 import java.awt.event.*;
3
4 public class DetectSourceDemo extends JFrame {
5
// Create four buttons
6
private JButton jbtNew = new JButton( "New" );
7
private JButton jbtOpen = new JButton( "Open" );
8
private JButton jbtSave = new JButton( "Save" );
9
private JButton jbtPrint = new JButton( "Print" );
10
11 public DetectSourceDemo() {
12 // Create a panel to hold buttons
13 JPanel panel = new JPanel();
14 panel.add(jbtNew);
15 panel.add(jbtOpen);
16 panel.add(jbtSave);
17 panel.add(jbtPrint);
18
 
 
Search WWH ::




Custom Search