Reputation: 1
I want to have a certain number of checkboxes that are in a ButtonGroup. These checkboxes send messages using an ItemListener when they get turned on and off, however I also want to be able uncheck all boxes as well.
How do I figure out the previous state of the checkbox before being clicked because the ButtonGroup makes it so when I try to uncheck my box, it sends another ActionEvent with the same true state the box was already in.
(I'm using checkboxes instead of radiobuttons because this is the current format of the whole window I'm working on so I want to keep it consistent on the panel).
Here is some starter code:
JPanel p = new JPanel();
ButtonGroup g = new ButtonGroup();
JCheckBox[] boxes = new JCheckBox[3];
String[] s = {"a", "b", "c"};
for (int i = 0 ; i < 3; i++) {
boxes[i] = new JCheckBox(s[i]);
boxes[i].addActionListener(obj -> {
JCheckBox box = (JCheckBox)obj.getSource();
if (box.isSelected()) {
g.clearSelection();
//System.out.println("ACTION: " + box.getText() + " " + box.isSelected());
}
});
boxes[i].addItemListener( obj-> {
JCheckBox box = (JCheckBox)obj.getSource();
if (!box.isSelected()) {
System.out.println(" ITEM: " + box.getText() + " " + box.isSelected());
}
});
g.add(boxes[i]);
p.add(boxes[i]);
}
Upvotes: 0
Views: 188
Reputation: 1
Figured it out. We do not need an ActionListener at all. We just need to modify the ButtonGroup class.
ButtonGroup g = new ButtonGroup() {
private ButtonModel prev;
@Override
public void setSelected(ButtonModel m, boolean b) {
prev = getSelection();
if (prev != null) {
if (prev.isSelected() && !b) {
clearSelection();
} else {
super.setSelected(m, b);
}
}
else {
super.setSelected(m, b);
}
}
};
Completed code:
JPanel p = new JPanel();
ButtonGroup g = new ButtonGroup() {
private ButtonModel prev;
@Override
public void setSelected(ButtonModel m, boolean b) {
prev = getSelection();
if (prev != null) {
if (prev.isSelected() && !b) {
clearSelection();
} else {
super.setSelected(m, b);
}
}
else {
super.setSelected(m, b);
}
}
};
JCheckBox[] boxes = new JCheckBox[3];
String[] s = {"a", "b", "c"};
for (int i = 0 ; i < 3; i++) {
boxes[i] = new JCheckBox(s[i]);
boxes[i].addItemListener( obj-> {
JCheckBox box = (JCheckBox)obj.getSource();
System.out.println(" ITEM: " + box.getText() + " " + box.isSelected());
});
g.add(boxes[i]);
p.add(boxes[i]);
}
Upvotes: 0