Using Major JavaFX Controls

JavaFX provides many GUI controls. This section covers the basic use of frequently used controls: check boxes, radio buttons, combo boxes, and sliders.

Checkbox

JavaFX includes many GUI controls, and they make it easy to build common GUIs. This section summarizes simple usage of these basic controls.

First, let’s look at check boxes. In JavaFX, this is the CheckBox class in the javafx.scene.control package. Create an instance as follows.

new Checkbox()
new Checkbox("display text")

If you pass text as an argument, that text is displayed next to the check box. As with Button, this display text can also be set with setText. The checked state can be handled as follows.

Get the checked state.

boolean variable = checkbox.isSelected();

Change the checked state.

checkbox.setSelected(boolean);

Checkbox can also have an action event. When the selection state changes, such as when the check box is clicked, an action event occurs. This event can be set with setOnAction, as with Button.

checkbox.setOnAction((ActionEvent) -> {
    // processing to perform
});

With a lambda expression, it can be written like this. This lets you run processing when the checked state changes.

The following is a simple example of using CheckBox.

package com.dekuma.javafx;
 
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
 
public class App extends Application {
    Label label;
    CheckBox check;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws Exception {
        label = new Label("This is JavaFX!");
        check = new CheckBox("체크박스");
        check.setSelected(true);
        check.setOnAction((ActionEvent)->{
            label.setText(check.isSelected() ? "Selected!" : "not selected...");
        });
         
        BorderPane pane = new BorderPane();
        pane.setTop(label);
        pane.setCenter(check);
        Scene scene = new Scene(pane, 320, 120);
        stage.setScene(scene);
        stage.show();
    }
 
}

When you run it, one check box appears. Clicking it displays “Selected!” or “not selected …” in the label.

RadioButton

Radio buttons are often used to select one item from several choices. They are also included in the javafx.scene.control package. Create the RadioButton class as follows.

new RadioButton()
new RadioButton("display text")

As with check boxes, display text can be changed with setText. The checked state can be handled with the isSelected and setSelected methods. Also, click handling can be set with an action event in the same way.

Get display text

String variable = radioButton.getText();

Set display text

radioButton.setText(String);

Get checked state

boolean variable = radioButton.isSelected();

Change checked state

radioButton.setSelected("boolean");

Set an action event

radioButton.setOnAction((ActionEvent) -> {
    // processing to perform
});

Radio buttons and check boxes are very similar, and their basic usage is almost the same. If you can use check boxes, you can understand the basics of radio buttons.

However, this alone is not enough to use radio buttons properly. You must understand grouping.

ToggleGroup

Radio buttons differ from check boxes because multiple controls are handled together. If you only create instances, they are simply buttons that become selected when clicked. Radio buttons should function as a group, with only one button selected at a time.

For this, use the ToggleGroup class. This class is in the javafx.scene.control package and, as the name suggests, manages multiple ON/OFF controls as one group. Create an instance as follows.

new ToggleGroup()

No arguments are required. RadioButton provides a method for setting the group it belongs to, and you set the ToggleGroup there.

radioButton.setToggleGroup(ToggleGroup);

If you set the same ToggleGroup on multiple RadioButton instances, they become one group, and only the clicked radio button is selected.

The following is a simple example using ToggleGroup.

package com.devkuma.javafx;
 
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
 
public class App extends Application {
    Label label;
    ToggleGroup group;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws Exception {
        label = new Label("This is JavaFX!");
        group = new ToggleGroup();
        RadioButton btn1 = new RadioButton("Male");
        btn1.setToggleGroup(group);
        btn1.setSelected(true);
        RadioButton btn2 = new RadioButton("Female");
        btn2.setToggleGroup(group);
        btn1.setOnAction((ActionEvent)->{
            label.setText("you are Male?");
        });
        btn2.setOnAction((ActionEvent)->{
            label.setText("you are Female?");
        });
         
        BorderPane pane = new BorderPane();
        pane.setTop(label);
        FlowPane flow = new FlowPane();
        flow.getChildren().add(btn1);
        flow.getChildren().add(btn2);
        pane.setCenter(flow);
        Scene scene = new Scene(pane, 320, 120);
        stage.setScene(scene);
        stage.show();
    }
 
}

Here, two RadioButton instances are created and assigned the same ToggleGroup. You can see that only the clicked radio button remains selected.

ComboBox

There are several GUI controls for selecting one item from multiple items. A representative one is the combo box. It is provided as the ComboBox class in the javafx.scene.control package.

new ComboBox()
new ComboBox("display contents")

A combo box displays items like a drop-down menu. You must set in advance what will be displayed in the menu. Pass the display contents to new ComboBox, and those contents are displayed as the menu.

The question is how to prepare the display contents. They must be prepared as an ObservableList instance from the javafx.collections package.

There are several ways to create this instance, but the easiest to understand is to use methods of the FXCollections class in the javafx.collections package.

ObservableList variable = FXCollections.observableArrayList(value1, value2, ...);

This creates an ObservableList instance. The arguments are the values displayed in the menu. Most commonly, String values are specified and displayed. With ObservableList, this is written as follows.

ObservableList<String> variable = FXCollections.observableArrayList(...);

Create the instance this way and pass it to the ComboBox constructor.

Values Retrieved from ComboBox

When a value is selected in a ComboBox, you can retrieve it as follows.

Object variable = comboBox.getValue();

Note that this is getValue, not getText. What you retrieve is not text itself, but the selected object. If the data is provided as ObservableList<String>, a String is returned. If the data were set as ObservableList<Integer>, an Integer would be returned.

Editable Setting

A ComboBox can also be configured to allow direct text input. Use the setEditable method.

comboBox.setEditable(boolean);

If you set this to true, the combo box becomes editable. Users can not only select from the menu but also enter text directly. In the case of direct input, the value obtained by getValue is a String. If you set display data other than String, be aware that menu selection and text input may cause different types of instances to be returned by getValue.

The following is a simple ComboBox example.

package com.devkuma.javafx;
 
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
 
public class App extends Application {
    Label label;
    ComboBox<String> combo;
     
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws Exception {
        label = new Label("This is JavaFX!");
        ObservableList<String> data = FXCollections.observableArrayList("One", "Two","Three");
        combo = new ComboBox<String>(data);
        combo.setOnAction((ActionEvent)->{
            label.setText(combo.getValue());
        });
        BorderPane pane = new BorderPane();
        pane.setTop(label);
        pane.setCenter(combo);
        Scene scene = new Scene(pane, 320, 120);
        stage.setScene(scene);
        stage.show();
    }
 
}

When an item is selected from ComboBox, it is displayed in the Label. Since ComboBox can also set action event handling with setOnAction, this example uses it for processing.

Slider

A slider is used to input a value in an analog style, such as “from here to there.” A slider lets the user drag the knob on a bar to set a value. It is provided as the Slider class in the javafx.scene.control package.

new Slider()
new Slider(minimum value, maximum value, current value)

If you create it without arguments, an instance is created with default settings. If you specify the minimum value, maximum value, and current value as double values, the user can select a value within that range.

Slider has detailed display-related properties, and by setting them, you can adjust its display in various ways.

Set the Display Orientation

slider.setOrientation(Orientation);

This sets whether the slider is vertical or horizontal. The argument is a field of the Orientation class in the javafx.geometry package. This class includes the following two class fields.

  • HORIZONTAL: value indicating horizontal orientation.
  • VERTICAL: value indicating vertical orientation.

Turn Tick Display On or Off

slider.setShowTickMarks(boolean);
slider.setShowTickLabels(boolean);

A slider can display numeric tick marks. setShowTickMarks controls whether tick marks are shown; if set to true, tick marks are displayed. setShowTickLabels displays values such as the minimum and maximum values along the ticks.

Snap Values to Ticks

slider.setSnapToTicks(boolean);

If this is set to true, the value is forced to align with displayed tick positions when dragged. If set to false, dragging is unrestricted and the value can be obtained as a fine-grained real number.

Manipulate the Value

double value = slider.getValue();
slider.setValue(double);

The value of Slider can be manipulated with getValue and setValue. The resulting value is a real number.

Here is a simple example.

package com.devkuma.javafx;
 
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
 
public class App extends Application {
    Label label;
    Slider slider;
    Button button;
     
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws Exception {
        label = new Label("This is JavaFX!");
        slider = new Slider(0, 100, 50);
        slider.setShowTickMarks(true);
        slider.setShowTickLabels(true);
        slider.setSnapToTicks(true);
        button = new Button("CLICK");
        button.setOnAction((ActionEvent)->{
            label.setText("VALUE: " + slider.getValue());
        });
        BorderPane pane = new BorderPane();
        pane.setTop(label);
        pane.setCenter(slider);
        pane.setBottom(button);
        Scene scene = new Scene(pane, 320, 120);
        stage.setScene(scene);
        stage.show();
    }
 
}

Drag the slider to set a suitable value, then click the button to display the current value. A separate button is used because the Slider class does not support action events.

However, other events are available, and you can use them to implement processing during operations. We will cover that again later.