Java – All in One → JavaFX ComboBox – Camposha

Java – All in One

Java – All in One

Java – All in One

JavaFX ComboBox

JavaFX ComboBox Tutorial and Example

In this tutorial we want to explore the JavaFX ComboBox. How to populate it with data then handle the selected item change events thus showing the selected item in an alert dialog.

Video Tutorial

What You Learn in This Tutorial

(a). What is a ComboBox?

A ComboBox is a dropdown control. Normally with ComboBoxes the user selects a single item from a dropdown. ComboBoxes are not new and have existed since the introduction graphical user interfaces. ComboBoxe make efficient usage of space. They allow you to render lists of items in a small space.

(b). How to Create a JavaFX ComboBox?

In JavaFX ComboBox is found in the javafx.scene.control package, like all other controls.

So first you have to import that package. Then given we are creating a JavaFX application your class has to derive from the javafx.application.Application, then ovveride the start() method.

You create a ComboBox by instantiating it:

    private final ComboBox mComboBox=new ComboBox();
(c). How to populate a ComboBox with a List

First you have to have that list, let’s say we convert a comma separated values into a list using the Arrays class’s asList() method:

        List<String> nebulas = Arrays.asList("Bernad 68","Horse Head","Cat's Eye","Boomerang","Witch Head","Own",
                "Pelican","Eagle","Orion","Black Widow","Helix","Elephant's Trunk","Snake","Ring","Ant","Cone","Flame","Rosette","Ghost Head");

Then we can loop through the items. For each iteration we add items into our ComboBox by first invoking the getItems(), then invoking the add() method where we pass the current value.


        for (String nebular : nebulas)
        {
            mComboBox.getItems().add(nebular);
        }
(d). How to set Default Value to ComboBox

Normally that defauly value is just a prompt or message but not part of the combobox data source. It prompts the user for example to select an item. We set it using the setValue() method.

        mComboBox.setValue("Select Item From ComboBox");

MrComboBox.java

Here’s the full code.

package mrcombobox;

import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class MrComboBox extends Application {

    private final ComboBox mComboBox=new ComboBox();
    /*
    The main entry point for all JavaFX applications. We pass the applications primary Stage
     */
    @Override
    public void start(Stage stage) throws Exception {
        Scene scene = new Scene(new Group());
        stage.setTitle("JavaFX ComboBox - Fill From List");
        stage.setWidth(550);
        stage.setHeight(550);

        Label titleLabel = new Label("List of Nebulas");
        titleLabel.setFont(new Font("Lucida", 20));

        populateData();
        handleSelection();

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(titleLabel, mComboBox);
        vbox.setAlignment(Pos.CENTER);

        Group group=((Group) scene.getRoot());
        group.getChildren().addAll(vbox);
        group.setLayoutX(100);

        stage.setScene(scene);
        stage.show();
    }
    /*
    Populate ComboBox with ArrayList data
     */
    private void populateData()
    {
        List<String> nebulas = Arrays.asList("Bernad 68","Horse Head","Cat's Eye","Boomerang","Witch Head","Own",
                "Pelican","Eagle","Orion","Black Widow","Helix","Elephant's Trunk","Snake","Ring","Ant","Cone","Flame","Rosette","Ghost Head");
        //Pass our source to `fromIterable()` method. Then subscribe thae consumer to the source.
        for (String nebular : nebulas)
        {
            mComboBox.getItems().add(nebular);
        }
        mComboBox.setValue("Select Item From ComboBox");
    }
    /*
     Handle ComboBox Selection
     */
    private void handleSelection()
    {
        mComboBox.setOnAction(event -> {
            String selectedItem = mComboBox.getSelectionModel().getSelectedItem().toString();
            Dialog d=new Alert(Alert.AlertType.INFORMATION,selectedItem);
            d.show();
        });
    }
    /*
    Main method
     */
    public static void main(String[] args) {
        Application.launch(args);
    }
}

Downloading and Running

This is the full code. Just copy it into your project it’s just a single file.

Leave a Reply

Your email address will not be published. Required fields are marked *

Price

Free

Rating

Not enough ratings to display
X