Reputation: 34
I want to have a Button Group in which either only one option is selected or none of them are. At the moment, I can get it to have no options ticked by default, and then if one of them is ticked only one of them can be ticked, but I also want to be able to untick the button that was selected. Is this possible?
EDIT: Ideally without having a clear all button, as it would ruin the symmetry of my GUI. Also, here is my code thus far:
ButtonGroup option = new ButtonGroup();
for(int i = 0; i < n; i++) {
JCheckBox check = new JCheckBox("", false);
option.add(check);
row3b.add(check);
}
Upvotes: 0
Views: 1921
Reputation: 1
I faced the same issue. ButtonGroup
didn't work well, thus I had to code this behavior manually.
I had two JCheckBoxs
, A and B, they can't be selected both at the same time; only one selected at a time or none.
I had to add actionListener
to both JCheckBoxs
, and had each JCheckBox
to clear the selection the other JCheckBox
.
Here is the code snippet :
JCheckBox A = new JCheckBox("A");
JCheckBox B = new JCheckBox("B");
A.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(A.isSelected()) {
if(B.isSelected()) {
B.setSelected(false);
}
}
}
});
B.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(B.isSelected()) {
if(A.isSelected()) {
A.setSelected(false);
}
}
}
});
Upvotes: 0
Reputation: 3874
This snippet demonstrates how you can clear selections using ButtonGroup.clearSelection()
:
//The buttons
JFrame frame = new JFrame("Button test");
JPanel panel = new JPanel();
JRadioButton btn1 = new JRadioButton("Button1");
JRadioButton btn2 = new JRadioButton("Button2");
JButton clearbutton = new JButton("Clear");
panel.add(btn1);
panel.add(btn2);
panel.add(clearbutton);
frame.add(panel);
frame.setVisible(true);
frame.pack();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(btn1);
btngroup.add(btn2);
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
clearbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear all selections
btngroup.clearSelection();
}
});
As you can see, this creates two JRadioButtons and adds them to group then makes a button that clears selections. Really simple. Or you could create your own radio button class that allows for the unchecking of the button, which is also doable relatively easily.
Upvotes: 0
Reputation: 17534
Just use the clearSelection()
method of ButtonGroup
:
Clears the selection such that none of the buttons in the ButtonGroup are selected.
Upvotes: 3