Java Reference
In-Depth Information
10
private JButton jbtPrint = new JButton( "Print" );
11
12 public FrameAsListenerDemo() {
13 // Create a panel to hold buttons
14 JPanel panel = new JPanel();
15 panel.add(jbtNew);
16 panel.add(jbtOpen);
17 panel.add(jbtSave);
18 panel.add(jbtPrint);
19
20 add(panel);
21
22
// Register listener with buttons
jbtNew.addActionListener( this );
register listeners
23
24 jbtOpen.addActionListener( this );
25 jbtSave.addActionListener( this );
26 jbtPrint.addActionListener( this );
27 }
28
29 @Override /** Implement actionPerformed */
30
31 if (e.getSource() == jbtNew)
32 System.out.println( "Process New" );
33 else if (e.getSource() == jbtOpen)
34 System.out.println( "Process Open" );
35 else if (e.getSource() == jbtSave)
36 System.out.println( "Process Save" );
37 else if (e.getSource() == jbtPrint)
38 System.out.println( "Process Print" );
39 }
40
41 /** Main method */
42 public static void main(String[] args) {
43 JFrame frame = new FrameAsListenerDemo();
44 frame.setTitle( "FrameAsListenerDemo" );
45 frame.setLocationRelativeTo( null ); // Center the frame
46 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
47 frame.pack();
48 frame.setVisible( true );
49 }
50 }
public void actionPerformed(ActionEvent e) {
handle event
The frame class extends JFrame and implements ActionListener (line 5), so the class is a lis-
tener class for action events. The listener is registered to four buttons (lines 23-26). When a but-
ton is clicked, the button fires an ActionEvent and invokes the listener's actionPerformed
method. The actionPerformed method checks the source of the event using the getSource()
method for the event (lines 31, 33, 35, 37) and determines which button fired the event.
This design is not desirable, however, because it puts too many responsibilities into one
class. It is better to design a listener class that is solely responsible for handling events, which
makes the code easy to read and easy to maintain.
You should define listener classes using either inner classes or anonymous inner classes—
choose whichever produces shorter, clearer, and cleaner code. In general, use anonymous inner
classes if the code in the listener is short and the listener is registered for one event source. Use
inner classes if the code in the listener is long or the listener is registered for multiple event sources.
Which way is preferred?
16.12
Why should you avoid defining the custom frame class that implements
ActionListener ?
Check
Point
16.13
What method do you use to get the source object from an event object e ?
 
Search WWH ::




Custom Search