javafx combobox

www‮gi.‬iftidea.com

In JavaFX, a ComboBox is a control that allows users to select a value from a pre-defined list of options. It is similar to a ChoiceBox, but with a built-in text input field that allows users to enter a new value that is not in the list.

Here's an example of how to create and use a ComboBox in a JavaFX application:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MyJavaFXApp extends Application {

    @Override
    public void start(Stage primaryStage) {
        // Create a list of options for the ComboBox
        ObservableList<String> options = FXCollections.observableArrayList(
            "Option 1", "Option 2", "Option 3"
        );
        
        // Create a new ComboBox and set the options
        ComboBox<String> comboBox = new ComboBox<>(options);
        comboBox.setPromptText("Select an option...");
        
        // Add the ComboBox to a VBox layout
        VBox layout = new VBox(comboBox);
        
        // Create a Scene object with the layout and set it on the stage
        Scene scene = new Scene(layout, 300, 200);
        primaryStage.setScene(scene);

        // Show the stage
        primaryStage.show();
    }

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

In this example, we create a ComboBox with a list of three options. We set the prompt text of the ComboBox to "Select an option...", which is displayed when no value is selected. We then add the ComboBox to a VBox layout and set the VBox as the root of the Scene. Finally, we display the scene on the stage using the show() method.

The ComboBox class provides a number of methods for configuring the appearance and behavior of the control. You can set the list of options using the setItems() method, set the prompt text using the setPromptText() method, and set the selected item using the setValue() method. You can also use the setOnAction() method to add an event handler that responds to changes in the selected item.