javaswingjtogglebutton

Is it possible to make a JToggleButton deselect other JToggleButton to have a similar effect to traditional radio buttons?


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.


Solution

  • Try adding your buttons to a ButtonGroup:

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