Radio Buttons in JavaFX and FXML 2

Radio buttons are like the brother to CheckBoxes, the only difference is that they can be setup to force the user to select ONLY ONE of them at a time.  The code to read the user selection is almost identical to CheckBoxes as you will see later.This post will show you how to create this ‘Car Order’ form using a GridPane and 3 radio buttons for the model. Screen Shot 2015-01-27 at 5.45.20 AM

Learn to Code!

Step 1 –  Imports

I’m not fully convinced I should always start with this step since it is an obvious one.

But for those that want to copy and paste this example you will need this part as well, for sure.

If not, don’t type it –  just allow NetBeans to add them as needed, and always choose the FX-version when there is more than one.


import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

Step 2 – Declare Objects Needed

3 Radio buttons, 4 labels, 2 CheckBoxes and a button.

We will also put things into 3 VBoxes and we need this new thing called a ToggleGroup for the radio buttons as well.


public class FXRadioButtons extends Application {
  RadioButton rdobase, rdosport, rdodeluxe;
  CheckBox chkextend, chkrust;
  Button btncalculate;
  Label lbltitle, lblbase, lblextra, lbltotal;
  VBox vbradio, vbcheck, vblabels;
  ToggleGroup group;

Step 3 – Make Radio Buttons

They are made the same way as everything else in this example – just supply a caption.  But here is where we also create the ToggleGroup and set each radio button to the same group.  This will allow the program to force the user to pick only 1 of the 3 items.

We are also ‘pre-selecting’ the first radio button here using ‘setSelected’

Lastly, we put all 3 radio buttons into a VBox.  See my tutorial on VBoxes if you need more background on these handly little containers.


 public void start(Stage primaryStage) {
 //make radio buttons
 rdobase=new RadioButton("Base Model $17,500");
 rdosport=new RadioButton("Sport Model $19,700");
 rdodeluxe=new RadioButton("Deluxe Model $23,100");
 //create group for radio buttons
 group=new ToggleGroup();
 //precheck 1st option
 //put radio buttons into vbox
 vbradio=new VBox(20, rdobase, rdosport, rdodeluxe);
 vbradio.setPadding(new Insets(10));

Step 4 – Make Checkboxes and Buttons

See my tutorial on CheckBoxes if you need more background on these too.  The button is the ONLY thing that will respond to user interaction so it is the only thing to attach the ‘handeButtonAction’ method to.

We also put these 3 guys into their OWN VBox too.


 //make checkboxes and order button
 chkextend=new CheckBox("Extended Warranty: add $500");
 chkrust=new CheckBox("Rust Undercoating: add $850");
 btncalculate=new Button("Calculate Total");
 btncalculate.setOnAction(e-> handleButtonAction(e));
 //put into vbox
 vbcheck=new VBox(20,chkextend,chkrust, btncalculate);
 vbcheck.setPadding(new Insets(10));

Step 5 – Make the Labels

The 1st label will stretch out over the top row of the gridpane.  It can have its text centered within itself using ‘setAlignment’.  It also gets its own styling too using the ‘setStyle’ method.

The other 3 labels get added to the 3rd VBox, and this VBox gets a bit of styling too – so it can stand out from the other 2 VBoxes.


//make top label 
 lbltitle=new Label("Order Your Car Today!");
 //make column 3 labels
 lblbase=new Label("Base: \t$");
 lblextra=new Label("Extras: \t$");
 lbltotal=new Label("Total: \t$");
 lbltitle.setStyle("-fx-font-size: 36px; 
    -fx-background-color: tan; -fx-text-fill:white;");
//add 3 labels to vbox
 vblabels=new VBox(20,lblbase, lblextra, lbltotal);
 vblabels.setPadding(new Insets(10)); 
 vblabels.setStyle("-fx-border-color: black;
    -fx-background-color: cornsilk;");

Step 6 – Make the GridPane

You can add entire rows to the GridPane with the ‘addRow’ method.  The first row just gets the title label and the next row gets the 3 VBoxes, to make up 3 columns in row 2.

The title also needs the ColumnSpan and HAlignment settings applied to it so it spreads out over 3 columns and stays in the middle.

The rest of this code is given when you create the file in NetBeans, but I did alter the size (500 x 175) and the title.

  //make gridpane
  GridPane root = new GridPane();
  //add title to top row, centered over 3 columns
  root.addRow(0, lbltitle);
  GridPane.setColumnSpan(lbltitle, 3);
  GridPane.setHalignment(lbltitle, HPos.CENTER);
  //add 2nd row of 3 vboxes
  root.addRow(1,vbradio, vbcheck, vblabels);
  //usual code - making it a 500 by 175 frame
  Scene scene = new Scene(root, 500, 175);
  primaryStage.setTitle("Car Order Form");

Step 7 – Write the Button’s Code

This is the method the button will run when its clicked on.  Just like CheckBoxes, we use the ‘isSelected’ method to see if a RadioButton has been chosen.  However since each CheckBox can be chosen independant of the other(s) we need a separate IF statement for each CheckBox, vs – 1 IF with 1 or more else-if / else expressions for RadioButtons.

Using if statements we charge a price based on what the user selected and print out the results into the 3 labels.  Viola!


 private void handleButtonAction(ActionEvent event) {
    int base, extra=0, total;
    //which single radio button is selected?
    if(rdobase.isSelected()) base=17500;
    else if(rdosport.isSelected()) base=19700;
    else base=21300; //then must be third one
    //which checkbox(es) selected-if any
    if(chkrust.isSelected()) extra+=850;
    if(chkextend.isSelected()) extra+=500;
    //calculate total and display everything
    lblbase.setText("Base: \t$" + base);
    lblextra.setText("Extras: \t$" + extra);
    lbltotal.setText("Total: \t$" + total);

Radio Buttons – the FXML Version

Step 1 – Declare @FXML Variables

Looking at the FX version, we need all those control variables declared here except for the Title label and the ToggleGroup.  Everything else gets referred to in the ‘handeButtonAction’ method so it needs to be declared.

This is one thing that annoys me a little – I wish you could declare things together in a group like you can in JavaFX but no – you have to declare each thing on its own line.  These will later get matched up in scene builder to the actual controls drawn on the screen.

public class FXMLDocumentController 
              implements Initializable {
    RadioButton rdobase;        
    RadioButton rdosport;        
    RadioButton rdodeluxe;
    CheckBox chkextend;
    CheckBox chkrust;      
    Button btncalculate;    
    Label lblbase;
    Label lblextra;
    Label lbltotal;

Step 2 – Compete the ‘HandleButtonAction’

No code required here as it can be copied from the JavaFX version.  It just has @FXML on top of it, and it will be connected to the button later on in SceneBuilder.

Step 3 – Design The FXML Interface With Scene Builder

This time around I am going to use Google slides to illustrate screen-shots from my YouTube version of this tutorial that cover the making of the FXML document.  This is different from my other posts so we will see how it goes – you will have to let me know if you like this format better, or the way I present the FXML side of things in other posts, such as the post about working with Checkboxes.

YouTube Video