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

Nishant Chatterjee KMS :

I have three JRadioButtons added to a JPanel. However, when I select one, I can select another one and the previous one selected stays selected. How can I make sure that only one is selected at a time?

My JPanel class, which is added by my main 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);
    }


}
Sebastian I. :

You can add the JRadioButtons in a ButtonGroup instance first. Here is a simple example:

// 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169649&siteId=1