Java Reference
In-Depth Information
19 add(panel);
20
21 // Create a listener
22 ButtonListener listener = new ButtonListener();
23
24 // Register listener with buttons
25 jbtNew.addActionListener(listener);
26 jbtOpen.addActionListener(listener);
27 jbtSave.addActionListener(listener);
28 jbtPrint.addActionListener(listener);
29 }
30
31 class ButtonListener implements ActionListener {
32 @Override
33
create listener
register listener
listener class
public void actionPerformed(ActionEvent e) {
handle event
if (e.getSource() == jbtNew)
34
35 System.out.println( "Process New" );
36
37 System.out.println( "Process Open" );
38
39 System.out.println( "Process Save" );
40
41 System.out.println( "Process Print" );
42 }
43 }
44
45 /** Main method */
46 public static void main(String[] args) {
47 JFrame frame = new DetectSourceDemo();
48 frame.setTitle( "DetectSourceDemo" );
49 frame.setLocationRelativeTo( null ); // Center the frame
50 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
51
52 frame.setVisible( true );
53 }
54 }
else if (e.getSource() == jbtOpen)
else if (e.getSource() == jbtSave)
else if (e.getSource() == jbtPrint)
frame.pack();
This program defines just one inner listener class (lines 31-43), creates a listener from the
class (line 22), and registers it to four buttons (lines 25-28). When a button is clicked, the but-
ton 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 34, 36, 38, 40) and determines which button fired the event.
Defining one listener class for handling a large number of events is efficient. In this case,
you create just one listener object. Using anonymous inner classes, you would create four lis-
tener objects.
You could also rewrite Listing 16.4 by defining the custom frame class that implements
ActionListener , as shown in Listing 16.6.
L ISTING 16.6 FrameAsListenerDemo.java
1 import javax.swing.*;
2 import java.awt.event.*;
3
4 public class FrameAsListenerDemo extends JFrame
5
implements ActionListener
{
implement ActionListener
6
// Create four buttons
7
private JButton jbtNew = new JButton( "New" );
8
private JButton jbtOpen = new JButton( "Open" );
9
private JButton jbtSave = new JButton( "Save" );
 
Search WWH ::




Custom Search