CheckBoxes in JavaFX and FXML 3


Checkboxes are handy little widgets that allow you to select one or more options at the same time.  You can either have your program watch for changes in a user selection right away (when the user clicks on or off a single checkbox) or in a separate button (like a ‘done’ button for example).  Here are 2 examples showing how to do this using both JavaFX and FXML  Screen Shot 2015-01-24 at 6.35.05 AM

Learn to Code!


 CheckBoxes in JavaFX

1 – Imports (I Often Overlook This Part)

Since you don’t actually type these (NetBeans adds them as needed) I don’t often show this part.  I am putting this here though to remind you that yes they ARE needed, and to make sure that you get the RIGHT import, as in some cases there are ‘awt’ or swing versions available – always choose the FX version when prompted by NetBeans.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

2 – Declare Controls Needed

We need 3 checkboxes and 2 labels.  We also need 2 VBoxes to contain the controls, one for the CheckBoxes and one for the Labels.  If you have never seen these before check out my post on using HBoxes and VBoxes.  I always like to do this at the top of the class outside of all methods.

public class CheckBoxDemo extends Application {
    
   //controls needed for app:
    CheckBox chksport1, chksport2, chksport3;
    Label lbltotal, lbllist;
   
   //2 VBoxes for the labels and checkboxes 
    VBox vbchecks, vblabels;

3 – Build the VBoxes

In the start method I begin by creating the 2 VBoxes and set the padding and spacing for each one to spread things out a little.

 

 @Override
    public void start(Stage primaryStage) {
       //vbox for checkboxes     
       vbchecks = new VBox();
       vbchecks.setSpacing(10);
       vbchecks.setPadding(new Insets(20));
       
       //vbox for labels
       vblabels = new VBox();
       vblabels.setSpacing(10);
       vblabels.setPadding(new Insets(20));

4 – Build the Controls

To make a checkbox is very easy – just pass the label for it into the constructor.  Labels are made the same way, of course.

       //make 3 checkboxes
       chksport1=new CheckBox("Hockey");
       chksport2=new CheckBox("Baseball");
       chksport3=new CheckBox("Football");
       
        //make 2 labels
       lbltotal=new Label("Sports chosen: 0");
       lbllist=new Label("None");

5 – Add Everything to Their VBoxes

By listing them in ‘addAll’, we can specify the order they get added to each VBox

 

//add all things to vboxes
vbchecks.getChildren().addAll(chksport1, chksport2, chksport3);
vblabels.getChildren().addAll(lbltotal, lbllist);

6 – Attach a Method to Each Checkbox

This will allow each checkbox to respond when it is clicked on by running a method.  All 3 will run the same method when they are clicked on.  We will define the method itself later in step 8.

   //attach click-method to all 3 checkboxes
   chksport1.setOnAction(e -> handleButtonAction(e));
   chksport2.setOnAction(e -> handleButtonAction(e));
   chksport3.setOnAction(e -> handleButtonAction(e));

7 – Make ‘Root’ a FlowPane and Add 2 VBoxes

By default, ‘root’ is a StackPane but we will change it to a FlowPane.  We only have to add the 2 VBoxes to it and everything inside the VBoxes get added automatically as well.  I am also spacing out the VBoxes with a horizontal gap.

The rest of the code is always given when you start a new JavaFX document in NetBeans.  You can modify the size and/or title if you want to

 

        //create main container and add 2 vboxes to it
        FlowPane root = new FlowPane();
        root.setHgap(20);
        root.getChildren().addAll(vbchecks, vblabels);
            
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

8 – Write the Checkbox Method

To see if a checkbox has been selected, you ask for its ‘selected()’ state which will be either TRUE or FALSE.  This method goes to each checkbox and asks if it has been selected.  For each one that is selected, we count it and add it’s text to a list.  Then we print the results to the 2 labels.

Remember – every time a checkbox is clicked (either ON or OFF) we need to run this method to update the status.  Our code will do that for us now.  But this is why we initialize count and choices to 0 and “” each time and recount/rebuild the list from scratch with each click of a checkbox.

 

  private void handleButtonAction(ActionEvent e) {
    int count=0;
    String choices="";
    if(chksport1.isSelected()){
        count++;
        choices+=chksport1.getText() + "\n";
     }
    if(chksport2.isSelected()){
        count++;
        choices+=chksport2.getText() + "\n"
     }
    if(chksport3.isSelected()){
        count++;
        choices+=chksport3.getText() + "\n";
     }
   lbltotal.setText("Sports chosen: " + count);
   lbllist.setText(choices);
 }

Learn to make a mobile app!

 CheckBoxes in FXML

1 Declare @FXML Variables in Controller

Only the ones you will be referring to in the Controller Code, which is all of them for this example.

Always one per line, always with @FXML on top

public class CheckBoxFXMLController implements Initializable {

    @FXML
    CheckBox chksport1;
    @FXML
    CheckBox chksport2;
    @FXML
    CheckBox chksport3;
    @FXML
    Label lbltotal;
    @FXML
    Label lbllist;
    

2 – Complete @FXML Method(s) in Controller

If you think this looks familiar well it should be.  This code is IDENTICAL to the FX version, except it has @FXML at the start to allow it to connect to something in the FXML document later (in step 8)

The initialize method is already provided for us, I just include it here as a point of reference.

@FXML
private void handleButtonAction(ActionEvent e) {
    int count=0;
    String choices="";
    if(chksport1.isSelected()){
        count++;
        choices+=chksport1.getText() + "\n";
     }
    if(chksport2.isSelected()){
        count++;
        choices+=chksport2.getText() + "\n"
     }
    if(chksport3.isSelected()){
        count++;
        choices+=chksport3.getText() + "\n";
     }
   lbltotal.setText("Sports chosen: " + count);
   lbllist.setText(choices);
 }
@Override
 public void initialize(URL url, ResourceBundle rb) {
        // TODO
  }       
}

Designing the FXML Document

3 – Open FXML Document in Scene Builder

This is what we are trying to ‘build’ (or draw as it were).

       Screen Shot 2015-01-24 at 6.55.47 AM

4 – Drag out CheckBoxes and Labels

These can be found in the Controls panel.

 Screen Shot 2015-01-24 at 6.47.29 AM

5 – Wrap Checkboxes in VBox

Shift-click each CheckBox to select them as a group.  Use menu Arrange -> Wrap In -> VBox.  You will now see the CheckBoxes organized in the Document Hierarchy within a VBox

 Screen Shot 2015-01-24 at 6.47.58 AMScreen Shot 2015-01-24 at 6.48.30 AM

6 – Set Layout For VBox

With the VBox selected in the Document Hierarchy, go to the Layout panel to set the padding and spacing.  We did this using code in the JavaFX version.

Screen Shot 2015-01-24 at 6.48.37 AM

7 – Change the Text in CheckBoxes and Labels

Using the Text property, or you can double-click each control to change the text as well.

Screen Shot 2015-01-24 at 6.48.55 AM

8 – Attach FX:Id to Everything and the ‘On Action’ to CheckBoxes

For a step with a lot of words, its pretty easy to do.  This can be found in the Code section for each control.  The labels do not need an OnAction connection, only the ‘fx:id’.  These are all being picked up automatically from the controller where you declared everything in the first 2 steps.

Screen Shot 2015-01-24 at 6.49.09 AM

9 – Add Style to The List Label (Optional)

In the Layout panel for the list label, you can add border color and padding.  This can also be done in JavaFX by passing a String to the setStyle method for any control.  I cover this in other posts, such as the switching scenes tutorial I did.

 Screen Shot 2015-01-24 at 6.49.38 AM

YouTube Video


3 thoughts on “CheckBoxes in JavaFX and FXML

Comments are closed.