问题描述
假设我们有一些 JRadioButton
属于相同的 ButtonGroup
,当用户点击 JRadioButton
时,它被选中.我想添加一个功能,当用户单击已选择的 JRadioButton
时,它会被取消选择,即整个 ButtonGroup
将不会选择 JRadioButton
.我已经搜索过哪些让我提示使用,ButtonGroup
方法,clearSelection.但问题是当用户点击已经选择的 JRadioButton 时,它不会生成任何 ItemStateChangeEvent
,这是通过点击其他未选择的 JRadioButton
生成的.
Let's say we are having some JRadioButton
s which belongs to same ButtonGroup
, when user clicks on a JRadioButton
it got selected. I want to add a feature that when user click on already selected JRadioButton
, it gets deselected, that is whole ButtonGroup
will have no JRadioButton
selected.I already searched which leads me hint to use, ButtonGroup
method, clearSelection. but problem is that when user clicks on already selected JRadioButton, it is not generating any ItemStateChangeEvent
, which is generating by clicking on other unselected JRadioButton
s.
推荐答案
或者,作为替代方法,覆盖 ButtonGroup#setSelected(...)
:
Or, as an alternate approach, override ButtonGroup#setSelected(...)
:
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
public class Test2 {
public JComponent makeUI() {
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(makePanel("Default ButtonGroup", new ButtonGroup()));
p.add(makePanel("Custom ButtonGroup", new ButtonGroup() {
private ButtonModel prevModel;
private boolean isAdjusting = false;
@Override public void setSelected(ButtonModel m, boolean b) {
if (isAdjusting) {
return;
}
if (m.equals(prevModel)) {
isAdjusting = true;
clearSelection();
isAdjusting = false;
} else {
super.setSelected(m, b);
}
prevModel = getSelection();
}
}));
return p;
}
private JComponent makePanel(String title, ButtonGroup g) {
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder(title));
for (String s: Arrays.asList("aaa", "bbb", "ccc")) {
AbstractButton r = new JRadioButton(s);
//AbstractButton r = new JToggleButton(s);
p.add(r);
g.add(r);
}
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new Test2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
这篇关于如何通过单击取消选择已选择的 JRadioButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!