JavaFX user interface control 1 – ChoiceBox ComboBox

1. Choice Box ChoiceBox

JavaFX’s ChoiceBox is a user interface control used to present a list of options to the user and allow the user to select one or more options from it. The following is a simple example of ChoiceBox and its usage introduction:

First, import the relevant classes of JavaFX:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

In a JavaFX application, create a ChoiceBox object and populate it with options:

public class Main extends Application {
@Override
public void start(Stage primaryStage) {
// Create a ChoiceBox object
ChoiceBox choiceBox = new ChoiceBox<>();

// Populate the options list
choiceBox.getItems().addAll(“Option 1”, “Option 2”, “Option 3”);

// set default selection
choiceBox.setValue(“Option 1”);

// create a layout and add ChoiceBox to it
VBox layout = new VBox();
layout.getChildren().add(choiceBox);

// create a scene and add the layout to it
Scene scene = new Scene(layout, 300, 200);

// set the scene and show the stage
primaryStage. setScene(scene);
primaryStage. show();
}

public static void main(String[] args) {
launch(args);
}
}

In this example, we create a ChoiceBox object containing three choices and add it to a vertical layout VBox. We set the default option to “Option 1”. Finally, we add the layout to the scene, and show the stage.

1.1 Character Converter

A StringConverter is required when using a complex object to back a ChoiceBox. This object serializes a string to and from the select box. For this program, it is only necessary to code toString() to replace the default toString() of the Pair object. (Both toString and fromString need to be implemented in order to compile.)

The empty object EMPTY_PAIR is used to prevent nullpointerexception. The return value of assetClass().getvalue() can be accessed and compared without adding special null handling logic.

public class ChoicesApp extends Application {

    // Create a ChoiceBox object
    private final ChoiceBox<Pair<String,String>> assetClass = new ChoiceBox<>();
    //Create an empty Pair object
    private final static Pair<String, String> EMPTY_PAIR = new Pair<>("", "");

    @Override
    public void start(Stage primaryStage) throws Exception {

        Label label = new Label("Asset Class:");
        assetClass.setPrefWidth(200);
        Button saveButton = new Button("Save");
        
        
        // create a layout and add ChoiceBox to it
        HBox hbox = new HBox(
                label,
                assetClass,
                saveButton);
        hbox.setSpacing( 10.0d );
        hbox.setAlignment(Pos.CENTER);
        hbox.setPadding( new Insets(40) );

        Scene scene = new Scene(hbox);

        initChoice();

        saveButton. setOnAction(
                (evt) -> System.out.println("saving " + assetClass.getValue())
        );

        primaryStage.setTitle("ChoicesApp");
        primaryStage. setScene( scene );
        primaryStage. show();

    }

    //Create complex object choiceBox
    private void initChoice() {

        List<Pair<String,String>> assetClasses = new ArrayList<>();
        assetClasses.add( new Pair("Equipment", "20000"));
        assetClasses.add( new Pair("Furniture", "21000"));
        assetClasses.add( new Pair("Investment", "22000"));

        assetClass.setConverter( new StringConverter<Pair<String,String>>() {
            @Override
            public String toString(Pair<String, String> pair) {
                return pair. getKey();
            }

            @Override
            public Pair<String, String> fromString(String string) {
                return null;
            }
        });

        assetClass.getItems().add( EMPTY_PAIR );
        assetClass.getItems().addAll( assetClasses );
        assetClass.setValue( EMPTY_PAIR );

    }

    public static void main(String[] args) {
        launch(args);
    }
}

2. Combo Box ComboBox

JavaFX’s ComboBox is a user interface control that combines a text box and a drop-down list to display a set of options to the user and allow the user to select one or more options from them. The following is a simple example and usage instructions of a ComboBox:

First, import the relevant classes of JavaFX:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

In a JavaFX application, create a ComboBox object and fill it with options:

public class ComboBoxTest extends Application {
    @Override
    public void start(Stage primaryStage) {
        // Create a ComboBox object
        ComboBox<String> comboBox = new ComboBox<>();

        // Populate the options list
        comboBox.setItems(FXCollections.observableArrayList("Option 1", "Option 2", "Option 3"));

        // set default selection
        comboBox.setValue("Option 1");

        // Create a layout and add the ComboBox to it
        VBox layout = new VBox();
        layout.getChildren().add(comboBox);

        // create a scene and add the layout to it
        Scene scene = new Scene(layout, 300, 200);

        // set the scene and show the stage
        primaryStage. setScene(scene);
        primaryStage. show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

In this example, we create a ComboBox object containing three options and add it to a vertical layout VBox. We set the default option to “Option 1”. Finally, we add the layout to the scene, and show the stage.

In addition to the above examples, ComboBox has some other features, such as setting the maximum number of visible rows, setting the maximum height of the drop-down list, setting event listeners, etc. You can customize the use of ComboBox according to your needs.

2.1 ComboBox setting selection callback

public class ComboBoxTest2 extends Application {

    // Create a ComboBox object
    private final ComboBox<Pair<String, String>> account = new ComboBox<>();

    private final static Pair<String, String> EMPTY_PAIR = new Pair<>("", "");

    @Override
    public void start(Stage primaryStage) throws Exception {

        Label accountsLabel = new Label("Account:");
        account.setPrefWidth(200);
        Button saveButton = new Button("Save");

        // Create a layout and add the ComboBox to it
        HBox hbox = new HBox(
                accountsLabel,
                account,
                saveButton);
        hbox.setSpacing( 10.0d );
        hbox.setAlignment(Pos.CENTER);
        hbox.setPadding( new Insets(40) );

        Scene scene = new Scene(hbox);
        //initialization
        initCombo();

        saveButton. setOnAction( (evt) -> {
            if( account. getValue(). equals(EMPTY_PAIR ) ) {
                System.out.println("no save needed; no item selected");
            } else {
                System.out.println("saving " + account.getValue());
            }
        });

        primaryStage.setTitle("CombosApp");
        primaryStage. setScene( scene );
        primaryStage. show();
    }

    private void initCombo() {

        List<Pair<String,String>> accounts = new ArrayList<>();

        accounts. add( new Pair<>("Auto Expense", "60000") );
        accounts. add( new Pair<>("Interest Expense", "61000") );
        accounts. add( new Pair<>("Office Expense", "62000") );
        accounts. add( new Pair<>("Salaries Expense", "63000") );

        account.getItems().add( EMPTY_PAIR );
        account. getItems(). addAll( accounts );
        account.setValue( EMPTY_PAIR );

        //Set the selected callback
        Callback<ListView<Pair<String,String>>, ListCell<Pair<String,String>>> factory =
                (lv) ->
                        new ListCell<Pair<String,String>>() {
                            @Override
                            protected void updateItem(Pair<String, String> item, boolean empty) {
                                super. updateItem(item, empty);
                                if(empty) {
                                    setText("");
                                } else {
                                    setText( item. getKey() );
                                }
                            }
                        };

        account. setCellFactory( factory );
        account.setButtonCell( factory.call( null ) );
    }

    public static void main(String[] args) {
        launch(args);
    }
}

If this document is not detailed enough, you can refer to Getting Started with JAVAFX Basics_哔哩哔哩_bilibili