-1

I would like to know if there is any way to style a JavaFX ComboBox programmatically. I have tried to use the method setStyle(String); and styled the button, but it doesn't affect the list

Is there any way to do that?

  • well ... something wrong in the code you are not showing ;) For future questions, please read http://stackoverflow.com/help/mcve and act accordingly. – kleopatra Apr 09 '18 at 09:06

2 Answers2

0

you can change (for example) the text fill color of the cells of the list in the ComboBox like this:

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;

public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 200, 200);
    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A", "B", "C", "D", "E");
    myComboBox
        .setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
          @Override
          public ListCell<String> call(ListView<String> param) {
            final ListCell<String> cell = new ListCell<String>() {
              {
                super.setPrefWidth(100);
              }

              @Override
              public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null) {
                  setText(item);
                  if (item.contains("A")) {
                    setTextFill(Color.RED);
                  } else if (item.contains("B")) {
                    setTextFill(Color.GREEN);
                  } else {
                    setTextFill(Color.BLACK);
                  }
                } else {
                  setText(null);
                }
              }
            };
            return cell;
          }
        });
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();
  }
}
lumo
  • 790
  • 1
  • 8
  • 23
0

I think better way how to do it is set CSS ID or CSS class in code. For example your comboBox.

yourComboBox.setId("fancybox");

or set class:

yourComboBox.getStyleClass().clear();
yourComboBox.getStyleClass().add("fancyboxes");

and then style them in CSS. then you can style almost everything on comboBox.

Example:

#fancyBox .cell {
    -fx-text-fill: #4059a9;
}

there are many different "extensions" what you can add after #fancyBox and then style it. (Extension I mean that ".cell" after #fancyBox) this can help you. Just keep searching.

Javafx combobox styling

Michal Moravik
  • 1,213
  • 1
  • 12
  • 23