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:

JavaScript

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

JavaScript

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