如何通过单击取消选择已选择的JRadioButton

时间:2016-06-02 17:13:55

标签: java swing jradiobutton

假设用户点击JRadioButton时,我们有一些属于同一ButtonGroup的{​​{1}}个JRadioButton。我想添加一项功能,当用户点击已选中的JRadioButton时,会取消选中该功能,即整个ButtonGroup将不会选择JRadioButton。 我已经搜索了导致我hint使用ButtonGroup方法,clearSelection。但问题是,当用户点击已经选择的JRadioButton时,它不会生成任何ItemStateChangeEvent,这是通过单击其他未选择的JRadioButton来生成的。

2 个答案:

答案 0 :(得分:2)

我会使用方法cited。由于JRadioButtonJToggleButton,因此鼠标手势可能会出现问题。我在封闭面板上使用MouseListener,在按钮上使用Key Bindings,如下所示。单击按钮周围的面板或按 escape 键清除ButtonGroup中所有按钮的选择。

image

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(...)