To get through this tutorial, you must already be able to create a basic form with 3 or 4 radio buttons on it. We are going to go over making and using these buttons in a functional example. To start, I create a project selecting Java Application and then the Next button. I rename my application to “RadioButtons”, you may name it whatever you want to, I then deselect (uncheck) the “Create Main Class” option, followed by Finish.
- Right Click on Source Packages and New -> Java Package, I name this radiobuttons.
- Right Click radiobuttons (if you have named it the same as I have) -> New -> JFrame Form, which I name RadioButtons, and click finish.
- From the Right hand side (maybe different for you), drag Button Group anywhere in your square panel and drop it (you won’t see any changes here).
- Now place your radio buttons, using the Radio Button (next to your Button Group). I place four for this example. I then shift-click (to select all of them).
- Right click your selection -> Select Properties. This step is where you group them together. When you look at the properties, there is an option for button Grouping (seen below). This will group them for our purposes here, select your buttonGroup (that was created in step 3). Note: If you don’t see a selection, you can go back to 3 now and carry out that step
- At this stage, if you were to click “Play” or Run -> Main Project, you will see the radio buttons in a GUI that are grouped (allowing only 1 of the 4 to be selected at a time).
- Now, to put these radio buttons to use, we will add a button, with a click listener and a text area. (Just drag and drop from the right hand group of objects).
- To add the click listener to the button, Right Click the button, select Properties. At the top of the pop up dialogue, select events -> scroll down to mouseClicked and select the … on the right hand side. This will take you to the picture below, where I named my event and selected Ok to close out dialogues.
- This will take you into the code where you can create your code to do what you want it to do. In this example, I am simply setting the text box to the value of the radio button that is selected. And here is the corresponding code, below:
- Press Play now.
There are a few things to note. If you are using their text in a calculation, you will need to cast it properly. There is most likely a better way to do this, but for beginner I believe this will get you started. Feel free to comment, as always.