Reputation: 7855
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?
Upvotes: 0
Views: 467
Reputation: 558
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
Upvotes: 3
Reputation: 837
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);
Upvotes: 0