繁体   English   中英

如何确保在 Java 中只选择了一个 JRadioButton?

[英]How Do I Make Sure Only One JRadioButton Is Selected In Java?

我在JPanel添加了三个JRadioButton 但是,当我选择一个时,我可以选择另一个,而上一个选择的保持选中状态。 如何确保一次只选择一个?

我的JPanel类,由我的主JFrame添加:

public class MainPanel extends JPanel {

    private static JRadioButton addHouse, addRoad, calculateDist;

    static {
        addHouse = new JRadioButton("Add House");
        addRoad = new JRadioButton("Add Road");
        calculateDist = new JRadioButton("Calculate Distance");
    }

    MainPanel() {
        setBackground(Color.WHITE);

        addHouse.setBounds(50, 50, 100, 50);
        addRoad.setBounds(50, 150, 100, 50);
        addHouse.setBounds(50, 250, 100, 50);

        addHouse.setBackground(Color.WHITE);
        addRoad.setBackground(Color.WHITE);
        calculateDist.setBackground(Color.WHITE);

        add(addHouse);
        add(addRoad);
        add(calculateDist);
    }


}

由于您没有分享完整的代码,我不知道如何在您的情况下做到这一点,但总的来说

可以这样做

ButtonGroup buttonGroup = new ButtonGroup() // create a button group , buttons in a button group knows how to behave together 
JRadioButton radioButton1 = new JRadioButton("R1"); // create your buttons 
JRadioButton radioButton2 = new JRadioButton("R2"); // as many you want

buttonGroup.add(radioButton1); // make them part of group
buttonGroup.add(radioButton2);
myJFrame.setLayout(new FlowLayout()); // or any layout you want
myJFrame.add(radioButton1);    // add buttons to jframe 
myJFrame.add(radioButton1); 

当按钮被添加到 JFrame(或任何其他容器)时,它们是 group 的一部分,因此 group 处理它们之间的通信,现在您一次只能检查一个,尝试注释 buttonGroup.add(); 你会失去这种行为的。

同样的事情可以手动实现,在这种情况下,您将在每次选择时跟踪所有其他单选按钮以检查其他单选按钮是否已经选中,然后取消选中它们,这很乏味,因此最好使用 ButtonGroup 类的 Swing

您可以先在ButtonGroup实例中添加JRadioButton 这是一个简单的例子:

// configure buttons bounds, background etc.

ButtonGroup buttonGroup= new ButtonGroup();
buttonGroup.add(addHouse);
buttonGroup.add(addRoad);
buttonGroup.add(calculateDist);

// add the buttons to the panel too.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM