Home Segments Top Top Previous Next

925: Mainline

You could define a different action listener for each text field and each button. If there are many components to which to listen, however, you should follow the less cumbersome practice of defining just one listener, which you connect to all the text fields and buttons you wish to have monitored. Then, you define the actionPerformed method such that it determines, when called, which component has produced the action event.

In the following definition, for example, there is just one listener, which is connected to all action-event-producing components. The actionPerformed method calls getSource with the action event as the target. This call produces the action-event-producing component, which actionPerformed matches against each text field and button. Then, having identified the action-event-producing component, actionPerformed calls an appropriate setter:

import java.awt.*; 
import java.util.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.*; 
public class RatingPanel extends JPanel implements RatingPanelInterface { 
 private int value1, value2, value3; 
 private JTextField field1, field2, field3; 
 private JButton button1Plus, button2Plus, button3Plus; 
 private JButton button1Minus, button2Minus, button3Minus; 
 RatingPanel (String x, String y, String z) { 
  setLayout(new GridLayout (3, 4, 3, 3)); 
  value1 = 0; value2 = 0; value3 = 0; 
  field1 = new JTextField(String.valueOf(value1), 20); 
  button1Plus = new JButton("+"); 
  button1Minus = new JButton("-"); 
  field2 = new JTextField(String.valueOf(value2), 20); 
  button2Plus = new JButton("+"); 
  button2Minus = new JButton("-"); 
  field3 = new JTextField(String.valueOf(value3), 20); 
  button3Plus = new JButton("+"); 
  button3Minus = new JButton("-"); 
  add(new JLabel (x));  
  add(field1); add(button1Minus); add(button1Plus); 
  add(new JLabel (y)); 
  add(field2); add(button2Minus); add(button2Plus); 
  add(new JLabel (z));  
  add(field3); add(button3Minus); add(button3Plus); 
  LocalActionListener listener = new LocalActionListener(); 
  field1.addActionListener(listener); 
  button1Plus.addActionListener(listener); 
  button1Minus.addActionListener(listener); 
  // Ditto for other text fields and buttons 
 } 
 // Setters and getters defined here 
 class LocalActionListener implements ActionListener { 
  public void actionPerformed(ActionEvent e) { 
   if        (e.getSource() == field1) {                                 
    setValue1(Integer.parseInt(field1.getText())); 
   } else if (e.getSource() == button1Plus) { 
    setValue1(value1 + 1); 
   } else if (e.getSource() == button1Minus) {  
    setValue1(value1 - 1); 
   } 
   // Ditto for other text fields and buttons 
  } 
 }  
 public Dimension getMinimumSize() {return new Dimension(300, 75);} 
 public Dimension getPreferredSize() {return new Dimension(300, 75);} 
}