0

I have the following JDialog implemented:

[ jToggleButton1 ]     [ jToggleButton2 ]     [ jToggleButton2 ]

I would like that when user presses (-toggles-) any of the JToggleButtons the other two change their state to unselected. This would emulate a classical "only one pushed at one time" button set.

I have implemented this behaviour using:

private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // do stuff
        btn1.setSelected(true);
        btn2.setSelected(false);
        btn3.setSelected(false);
}

private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // do stuff
        btn1.setSelected(false);
        btn2.setSelected(true);
        btn3.setSelected(false);
}

private void btn3ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // do stuff
        btn1.setSelected(false);
        btn2.setSelected(false);
        btn3.setSelected(true);
}

Although the example shown has 3 buttons my real scenario has like 15/20 buttons. This way of implementing the functionality is clearly not efficient.

  1. Is there any other design pattern to automatically have selected just one?
  2. Do JToggleButtons have implemented any feature that could be used?

Note: In case it is relevant, I am using Netbeans integrated UI editor to develop all Java swing JFrames/JDialogs.

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • Note: the ActionListener is invoked every time you click the button. The logic you posted seems to indicate you only want to invoke the logic when the button is not currently selected. If so, then you should use an `ItemListener` on the toggle button then you can execute the logic only when the button is currently not selected. See [How to Write an ItemListener](https://docs.oracle.com/javase/tutorial/uiswing/events/itemlistener.html). – camickr Nov 09 '19 at 16:01
  • Thanks for the clarification. In this specific case I do not actually care as pushing the button when it is already selected will just update the main window to exactly the same state it is right now, but in others it might be relevant so it is good to know how to properly implement an `ItemListener`. – M.E. Nov 09 '19 at 16:24

2 Answers2

2

Try adding your buttons to a ButtonGroup:

ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
...

BrianY
  • 195
  • 10
  • As a side note: this can be done also using Netbeans IDE UI builder. A "Button Group" object needs to be drag and drow (apparently is not visible) and then you select all buttons and modify "buttonGroup" property. – M.E. Nov 09 '19 at 15:42
0

A classic pattern is to create a single actionlistener function that toggle off (deselect in your case) all your buttons then get the source of action and toggle it on. In the end you set this actionlistener on all your buttons.

sed lex
  • 70
  • 1
  • 9