How to make a Searchable CheckComboBox in JavaFX and ControlsFX

119 Views Asked by At

For an example of what I mean, we can look to Microsoft Excel. What I want is something like this: Microsoft Excel Searchable CheckComboBox

I'm using JavaFX 21 and ControlsFX 11.2 and am using the ControlsFX CheckComboBox at the moment, it works great, but I really need the CheckComboBox to be searchable or at least prefix searchable since it's very difficult to scroll through the list when it gets long.

Here is the controlsFX CheckComboBox I have (you can see how annoying it would be to scroll through this):

ControlsFX Default CheckComboBox

The ControlsFX SearchableComboBox is also great, but only allows you to pick one thing at a time and the multi-select capability is a necessity.

ControlsFX Default SearchableComboBox Example

What I really need is for these two to come together and have a baby. But I can't find the best approach. I tried implementing a CheckComboBoxUtils class, but it didn't seem to work as it still just renders itself as a regular CheckComboBox in my application (I am a bit of a Java/JavaFX novice).

Here is my CheckComboBoxUtils class where I try to add the search functionality:

package com.cartunesks.casa_pos;
import org.controlsfx.control.CheckComboBox;

import javafx.collections.ObservableList;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;

public class CheckComboBoxUtils {

    public static void makeSearchable(CheckComboBox<String> checkComboBox) {
        TextField searchField = new TextField();
        searchField.setPromptText("Search");

        StackPane button = (StackPane) checkComboBox.lookup(".combo-box-base");
        button.getChildren().add(0, searchField);

        ObservableList<String> items = checkComboBox.getItems();

        searchField.textProperty().addListener((observable, oldValue, newValue) -> {
            checkComboBox.getCheckModel().clearChecks(); // Clear checks when searching
            if (newValue.isEmpty()) {
                checkComboBox.getItems().setAll(items); // Restore full list when empty
                return;
            }
            ObservableList<String> filteredItems = items.filtered(item -> item.toString().toLowerCase().contains(newValue.toLowerCase()));
            checkComboBox.getItems().setAll(filteredItems);
        });
    }
}

And i call it like so: CheckComboBoxUtils.makeSearchable(makeCheckComboBox);

I'm open to other solutions if this is difficult. Like maybe adapting the ControlsFX CheckListView and adding a search bar that dynamically filters the List of items? Just an Idea I had but it's really not optimal since I'd prefer to just make the existing CheckComboBox searchable.

0

There are 0 best solutions below