Skip to content
Advertisement

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

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


}

Advertisement

Answer

As you didn’t share the complete code i can’t tell how to do it in your case but in general

It can be done like that

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); 

when buttons were added to JFrame (or any other container) they were part of a group , so group handles the communications between them, now you can check only one at a time, try commenting buttonGroup.add(); you will loose that behaveiour .

Same thing can be achieved manually , it that case you will track all other radio buttons at every selection to check if others are already check and then uncheck them which is tedious so better use ButtonGroup class of swing

Advertisement