我正在尝试在JavaFX Tableview中设置单元格中的文本样式。我的模型有StringProperty title, description;
和BooleanProperty warning;
public class MyItem {
@FXML
private final StringProperty title = new SimpleStringProperty();
@FXML
private final StringProperty description = new SimpleStringProperty();
@FXML
private final BooleanProperty warning = new SimpleBooleanProperty();
//...
}
表格应为title
和description
。说明始终为-fx-font-weight: normal
。如果-fx-font-weight: bold
和warning
,标题为-fx-font-weight: normal
。这是一个有效的POJO方法。
column.setCellFactory(new Callback<TableColumn<Message, String>, TableCell<Message, String>>() {
public TableCell<Message, String> call(TableColumn<Message, String> param) {
return new TableCell<Message, String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || null == getTableRow() || null == getTableRow().getItem()) {
setText(null);
} else {
MyItem m = (MyItem) this.getTableRow().getItem();
if (null != m) {
setText(m.getTitle());
String style = m.isWarning()? "-fx-font-weight: bold" : "-fx-font-weight: normal";
setStyle(style);
}
}
}
};
}
});
我想将样式移到FXML和CSS。这是我试过的:
public class MyController{
@FXML
private TableView myTable;
@FXML
private TableColumn<MyItem, String> titleColumn;
@FXML
private TableColumn<MyItem, String> descriptionColumn;
//...
}
<content>
<TableView styleClass="fxml-table-style" stylesheets="@my_table_style.css" fx:id="myTable" >
<columns>
<TableColumn text="Title">
<cellValueFactory><PropertyValueFactory property="title" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Body">
<cellValueFactory><PropertyValueFactory property="description" />
</cellValueFactory>
</TableColumn>
</columns>
</TableColumn>
</columns>
如果列是标题和行isWarning
,如何告诉Java&#34;使用custom-style-1;使用custom-style-2否则&#34; ?
答案 0 :(得分:2)
使用CSS可以做的一件事是写入选择器,它考虑了Node
的父级。
在警告属性为TableRow
的{{1}}中添加一个preudoclass是合适的:
true
public class WarningRowFactory implements Callback<TableView<MyItem>, TableRow<MyItem>> {
private static final PseudoClass WARNING = PseudoClass.getPseudoClass("warning");
@Override
public TableRow<MyItem> call(TableView<MyItem> table) {
return new TableRow<MyItem>() {
private final InvalidationListener listener = observable -> pseudoClassStateChanged(WARNING, getItem() != null && getItem().isWarning());
@Override
public void updateItem(MyItem item, boolean empty) {
if (getItem() != null) {
getItem().warningProperty().removeListener(listener);
}
super.updateItem(item, empty);
if (item != null) {
item.warningProperty().addListener(listener);
}
listener.invalidated(null);
}
};
}
}
<TableView styleClass="fxml-table-style" stylesheets="@my_table_style.css" fx:id="myTable" >
<rowFactory>
<WarningRowFactory />
</rowFactory>
...