【发布时间】:2018-02-09 14:12:20
【问题描述】:
我想根据该行中的项目在 TableView 中呈现一个完整的行。我用的是TableView.setRowFactory,但是好像不行。
正如您在代码中看到的那样,如果该行中人员的姓氏是“Smith”,则该行应该使用不同的文本颜色呈现。
如果我使用 TableColumn.setCellFactory,相同的代码也可以工作。但我不想在所有不同的单元工厂中复制必要的代码。
我的错误在哪里?
public class TableViewTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
final Scene scene = new Scene(createContents());
scene.getStylesheets().add(getClass().getResource("test.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
private Pane createContents() {
final ObservableList<Person> items = FXCollections.observableArrayList(
new Person("John", "Smith"), new Person("Mary", "Smith"),
new Person("William", "Young"));
final TableView<Person> table = new TableView<>(items);
final TableColumn<Person, String> c1 = new TableColumn<>("First name");
c1.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getFName()));
final TableColumn<Person, String> c2 = new TableColumn<>("Last name");
c2.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getLName()));
table.getColumns().setAll(c1, c2);
table.setRowFactory(param -> new TableRow<Person>() {
protected void updateItem(Person item, boolean empty) {
super.updateItem(item, empty);
getStyleClass().remove("own-cell");
if (item != null && item.getLName().equals("Smith")) {
getStyleClass().add("own-cell");
}
};
});
return new HBox(table);
}
}
这是只有一种样式的简单样式表 test.css:
.table-row-cell:filled .own-cell {
-fx-text-fill: cyan;
}
【问题讨论】: