JavaFX TableView:如何将条件单元格样式移动到FXML/CSS?
问题描述:
我想在JavaFX Tableview中的单元格中设置文本样式。我的模型有StringProperty title, description;
和BooleanProperty warning;
JavaFX TableView:如何将条件单元格样式移动到FXML/CSS?
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
。如果是warning
和-fx-font-weight: normal
,则标题为-fx-font-weight: bold
。这是一个可用的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>
如何告诉Java的“如果使用自定义样式1列标题和行isWarning
;使用自定义风格的-2,否则”?
答
你可以用CSS做的一件事是编写选择器,考虑到Node
的父母。
这将是适合于preudoclass添加到TableRow
为什么会产生警告属性是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>
...
.table-row-cell .table-cell {
-fx-font-weight: normal;
}
.table-row-cell:warning .table-cell {
-fx-font-weight: bold;
}
可以移动的实际样式规则('“-fx-字体 - 重量:粗体“:”-fx-font-weight:normal“'),但条件部分将需要保留在您的单元格工厂的Java中。你可以让Java代码开关一个伪类。 –