0

I have two JRadioButton objects with an ActionListener:

    for (JRadioButton b : rightRButtons) {
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals("Unidade")) {
                    disableAllComponents(divisiblePanel);
                    enableAllComponents(unityPanel);
                } else if (e.getActionCommand().equals("Divisível")) {
                    disableAllComponents(unityPanel);
                    enableAllComponents(divisiblePanel);
                }
            }
        });
    }

Somewhere in the code, I select one of them: rdbtnCreationDivisible.setSelected(true);

Those radio buttons, once clicked, are supposed to disable all the components on their respective panels. When I select them using the setSelected method, the components don't get disabled. How can I trigger an action command artificially, so that the ActionListener can "catch" the command?

Ericson Willians
  • 7,606
  • 11
  • 63
  • 114

2 Answers2

3

A couple of things you could try:

First, you could loop through all the ActionListeners added to your button, then call it's actionPerformed() method, passing in a ActionEvent with whatever ActionCommand you like:

     for(ActionListener al : b.getActionListeners()) {
                al.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Unidade") { });
            }

Another option would be to replace your ActionListener with an ItemListener. This would get called when the button is selected/deselected, as opposed to being clicked on:

     b.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    //Will get called when you change selection using .setSelected()
                }
            });

Nemi has more information on using an ItemListener instead of an ActionListener on their answer here: Detecting a JRadioButton state change

Community
  • 1
  • 1
Gulllie
  • 523
  • 6
  • 21
0

You can create your own event and then pass it to dispatchEvent.

rdbtnCreationDivisible.setSelected(true);
ActionEvent fakeEvent = new ActionEvent(rdbtnCreationDivisible,
        ActionEvent.ACTION_PERFORMED, "Divisível");
rdbtnCreationDivisible.dispatchEvent(fakeEvent);
Alden
  • 837
  • 1
  • 6
  • 15