Action Listener Review
- Many components call an action listener in response to a user
action (JButton, JMenuItem, JTextField, etc). An action listener is
any object that implements the
ActionListener
interface. - The
ActionListener
interface requires that the class define anactionPerformed(ActionEvent e)
method. - Call the component's
addActionListener(...)
method, passing a parameter which is an object implementingActionListener
. - Common ways to implement action listeners follow.
1. One shared action listener (this) - Not great.
The class which defines the graphical user interface implements
ActionListener
. The component uses this
for the action listener.
myButton.addActionListener(this);
Example p 234.
This doesn't scale -- what if there is more than one component that needs an action listener?
2. Anonymous inner class listener (so-so)
JButton b1 = new JButton("Hello"); b1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // do something for button b1 } } );
- Convenient.
- Often mixes listeners into other code. (bad)
- Can't share listeners.
3. Named inner class listener (better)
ActionListener myHelloListener = new HelloListener(): JButton b1 = new JButton("Hello"); b1.addActionListener(myHelloListener); . . . class HelloListener implements ActionListener { public void actionPerformed(ActionEvent e) { // do something for button b1 } }
- Relatively convenient.
- Separates listeners from other code. (good)
- Can easily share listeners.
4. Subclassing AbstractActionListener (very good)
AbstractAction exitAction = new AbstractAction() { public void actionPerformed( ActionEvent e ) { if (gCurrentSkeema.isDirty()) { int response = JOptionPane.showConfirmDialog(xc_window, "Exit without saving changes?"); if (response == JOptionPane.YES_OPTION) { System.exit(0); } } else { System.exit(0); // Not dirty, can quit. } } };