JavaFX ComboBox项目上的文本颜色仅在首次选择后更改

我正在使用Windows 7中的SceneBuilder 2.0在e(fx)clipse中从Java 8.0构建JavaFx中的输入表单。

我有一个简单的String ComboBox,并希望更改列表和所选字符串中字体的颜色和大小。 我使用的CSS代码更改了所选项目上的文本。 但是,第一次删除列表时,它是黑色默认字体。 第二次,所有项目的字体颜色和大小已更改为正确的值。

如何使字体列表以正确的颜色和大小启动?

这是我的Controller类中的initialize方法的简化代码:

ObservableList types = FXCollections.observableArrayList ( "large", "medium", "small" ); comboBox.setItems( types ); 

和当前的css:

 #comboBox .list-cell { -fx-font-family: arial; -fx-font-size: 16px; -fx-text-fill: #a0522d; } 

你必须创建一个CellFactory,你不能使用CSS(我不知道为什么,但这是我能让它工作的唯一方法):

 import javafx.application.Application; import javafx.collections.FXCollections; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.util.Callback; public class Mainu extends Application { @Override public void start(Stage stage) throws Exception { ComboBox cb = new ComboBox(); cb.setItems(FXCollections.observableArrayList("Foo","Bar","777","Batman")); cb.setCellFactory(new Callback, ListCell>() { @Override public ListCell call(ListView p) { return new ListCell() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (item != null) { setText(item); //This won't work for the first time but will be the one //used in the next calls getStyleClass().add("my-list-cell"); setTextFill(Color.RED); //size in px setFont(Font.font(16)); } } }; } }); cb.getSelectionModel().selectFirst(); Pane root = new Pane(); root.getChildren().add(cb); Scene scene = new Scene(root); scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm()); stage.setScene(scene); stage.show(); } public static void main(String[] args) {launch(args);} } 

尽管您使用的是标准API,但我相信您也应该在CSS使用它并在CSS指定第一次必须以编程方式设置,因为这对于维护您的软件的任何人都很有用。

style.css文件

 .combo-box .cell{ -fx-text-fill: blue; -fx-font: 16px "Arial"; } .my-list-cell { -fx-text-fill: blue; -fx-font: 16px "Arial"; /* No alternate highlighting */ -fx-background-color: #FFF; } 

奇怪的细节:对于JavaFX 2,您可以通过CSS设置它,但仍然必须使用CellFactory。