Search code examples
csscomboboxstylesheetjavafx-8text-styling

JavaFX 8 - How to change the color of the prompt text of a NOT editable combobox via CSS?


The title says everything. I want to change the color of the prompt text of a not editable combobox, so that the text has the same color like the prompt text of a editable combobox. In my CSS-file I tried to use -fx-prompt-text-fill in .combo-box, .combo-box-base, .combo-box-base .text-field and .combo-box-base .text-input, but nothing worked.

What styleclass do I have to use?


Solution

  • When the ComboBox is not editable, there is no TextField, and the property -fx-prompt-text-fill is no longer valid, since the control displayed instead, a ListCell, doesn't extend TextInputControl.

    In order to set the style of this cell, we can provide our custom styled ListCell:

    @Override
    public void start(Stage primaryStage) {
        ComboBox comboBox = new ComboBox();
        comboBox.getItems().addAll("Item 1", "Item 2", "Item 3");
        comboBox.setPromptText("Click to select");
        comboBox.setEditable(false);
    
        comboBox.setButtonCell(new ListCell(){
    
            @Override
            protected void updateItem(Object item, boolean empty) {
                super.updateItem(item, empty); 
                if(empty || item==null){
                    // styled like -fx-prompt-text-fill:
                    setStyle("-fx-text-fill: derive(-fx-control-inner-background,-30%)");
                } else {
                    setStyle("-fx-text-fill: -fx-text-inner-color");
                    setText(item.toString());
                }
            }
    
        });
    
        Scene scene = new Scene(new StackPane(comboBox), 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }