MontaWiso
MontaWiso

Reputation: 99

How to add a custom css style for specific item in a combo/choice box in JavaFx?

Screen Capture

I am using javaFx, and I want to mimic this control. Specificly the link in the bottom of the menu !!
is it possible to do it with css only or without creating a custom control?

Upvotes: 1

Views: 116

Answers (1)

James_D
James_D

Reputation: 209299

There is no need to implement a custom control, but you do need a cell factory to do this. The basic idea is to add a style class to the cell if it requires it, and remove it if not. So you can do, for example:

final String cellStyleClass = "my-combo-box-cell" ;

ComboBox<String> combo = new ComboBox<>();
combo.setCellFactory(listView -> new ListCell<String>() {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty) ;
        getStyleClass().remove(cellStyleClass);
        if (empty) {
            setText(null);
        } else {
            setText(item);
            if (/* needs style class */) {
                getStyleClass().add(cellStyleClass);
            }
        }
    }
});

The test to see if you need to add the style class can obviously reference the item, etc.

Now in your CSS file you can style the cell as you need it:

.my-combo-box-cell {
    /* specific styles here... */
}

Upvotes: 1

Related Questions