如何确定在Java中仅选择了一个JRadioButton?

问题描述 投票:0回答:1

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

我的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);
    }


}
java jradiobutton
1个回答
0
投票

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

// 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.
© www.soinside.com 2019 - 2024. All rights reserved.