How to add radio buttons in java

Adding radio buttons in Java seems to be simple, what we do just add them in the JFrame, but it's not just that. You won't be able to achieve the desired result. I will show that mistake also. Ok, let's get started then.

Adding Radio Buttons

Firstly add the radio buttons to the JFrame and set accordingly.

radio buttons

Now run your program and you will notice that you are able to select all the buttons added to JFrame. This was the mistake I discussing above.


Adding ButtonGroup

So, to remove this discrepancy you just have to include the ButtonGroup from the Pallete.

Button Group

And change the button group property of the radio buttons by selecting the ButtonGroup you have dragged earlier.

JRadioButton Property

Now it will be working smoothly.

radio buttons

Now let's see how this can be done programmatically.

ButtonGroup buttonGroup1 = new ButtonGroup();
JRadioButton jRadioButton1 = new JRadioButton();
JRadioButton jRadioButton2 = new JRadioButton();



And you will get the same result.

The following two tabs change content below.

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...