2

I was wondering whether there is any other way to handle and event coming from any of N controls, which would read the ActionCommand value and act based on that. So far I basically have a defitinion of ActionListener which I add to each of the controls individually. For instance, if I have 50 checkboxes, I would like to write a method like

void process(){ 
    getCommandValueAndDoSth();
}

but rather than instantiate ActionListener for all the checkboxes, I would like just to control all the checkboxes.

Bober02
  • 15,034
  • 31
  • 92
  • 178

3 Answers3

3

You can have one listener for all of your components.

ActionListener al = new ActionListener {
  @Override
  public void actionPerformed(ActionEvent e) {
    // either do it like this
    process(e.getActionCommand());
    // or like this to distinguish between the controls
    if (e.getSource() == firstElement) processChangeInFirstElement();
    else if (e.getSource() == secondElement) processChangeInSecondElement();
    // etc
  }
}

Component firstElement = new JCheckBox("asdf");
firstElement.addActionListener(al);

Component secondElement = new JTextField();
secondElement.addActionListener(al);

If you need to have multiple types of listeners (ChangeListener, MouseListener, ActionListener, KeyListener, ...), then you have one instance of each of those listener types and apply them to the corresponding components.

brimborium
  • 9,362
  • 9
  • 48
  • 76
1

You can attach the same ActionListener to multiple components (e.g. to all your Checkboxes). The handler just needs to be able to derive all the required information from the ActionEvent (if required it can get to the component using event.getSource()).

Durandal
  • 19,919
  • 4
  • 36
  • 70
0

In my case I just wanted to know if any control in the window had been changed and should allow the user to "apply" those changes. You can actually add them pretty easily with lambdas. Below are examples for JCheckBox, JComboBox<>, and JXDatePicker. Both JTextField/JTextArea are a little more complicated and require document listeners.

chckbx.addItemListener(e -> process()); //Check box itemListeners don't trigger when hovering
comboBox.addActionListener(e -> process()); //Triggered when selection changes
datePicker.addActionListener(e -> process()); //When date changes
addChangeListener(txtField, e -> process()); //Text field needs a documentListener

The code for the text field's document listener addChangeListener.

MasterHD
  • 2,264
  • 1
  • 32
  • 41