AdnanArch
AdnanArch

Reputation: 116

How to implement a ComboBox Act like a Search Field in JavaFx?

I am trying to implement a ComboBox having functionality of searching items in it. the user will search the item and combobox will show the item and with the help of up, down keys or mouse i can select the item from the combobox.

i have come with this code so far but it is not working correctly.

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 Test extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.setEditable(true);

        ObservableList<String> items = FXCollections.observableArrayList(
                "Apple", "Banana", "Cherry", "Grape", "Lemon", "Orange", "Strawberry"
        );

        comboBox.setItems(items);

        // Create a filtered list that updates as the user types
        ObservableList<String> filteredList = FXCollections.observableArrayList(items);
        comboBox.getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
            String filter = newValue.toLowerCase();
            if (filter.isEmpty()) {
                // If the text is empty, show all items
                comboBox.setItems(items);
            } else {
                filteredList.clear();
                for (String item : items) {
                    if (item.toLowerCase().contains(filter)) {
                        filteredList.add(item);
                    }
                }
                comboBox.setItems(filteredList);
                comboBox.show();
            }
        });

        VBox root = new VBox(comboBox);
        Scene scene = new Scene(root, 300, 200);

        primaryStage.setTitle("Searchable ComboBox Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Upvotes: 1

Views: 268

Answers (0)

Related Questions