假设用户点击JRadioButton
时,我们有一些属于同一ButtonGroup
的{{1}}个JRadioButton
。我想添加一项功能,当用户点击已选中的JRadioButton
时,会取消选中该功能,即整个ButtonGroup
将不会选择JRadioButton
。
我已经搜索了导致我hint使用ButtonGroup
方法,clearSelection。但问题是,当用户点击已经选择的JRadioButton时,它不会生成任何ItemStateChangeEvent
,这是通过单击其他未选择的JRadioButton
来生成的。
答案 0 :(得分:2)
我会使用方法cited。由于JRadioButton
是JToggleButton
,因此鼠标手势可能会出现问题。我在封闭面板上使用MouseListener
,在按钮上使用Key Bindings,如下所示。单击按钮周围的面板或按 escape 键清除ButtonGroup
中所有按钮的选择。
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.KeyStroke;
/**
* @see https://stackoverflow.com/a/37599961/230513
*/
public class Test {
private static final String UNSELECT = "UNSELECT";
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new GridLayout(1, 0, 5, 5));
p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
ButtonGroup group = new ButtonGroup();
JRadioButton r1 = create("One", group);
JRadioButton r2 = create("Two", group);
p.add(r1);
p.add(r2);
p.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
group.clearSelection();
}
});
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JRadioButton create(String name, ButtonGroup group) {
JRadioButton b = new JRadioButton(name);
group.add(b);
b.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), UNSELECT);
b.getActionMap().put(UNSELECT, new AbstractAction(UNSELECT) {
@Override
public void actionPerformed(ActionEvent e) {
group.clearSelection();
}
});
return b;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
答案 1 :(得分:2)
或者,作为替代方法,覆盖g++ -g -lpthread ~/temp/temp.cpp -o temp
:
ButtonGroup#setSelected(...)