【发布时间】:2019-10-16 00:13:38
【问题描述】:
我必须实现很多自定义的 TableCell 行为依赖于模型的变化。我可以设法以某种方式获得预期的结果,但我认为在很多情况下这是一种解决方法,而不是一个非常好的解决方案。 我已经使用绑定/监听器来达到预期的结果,但我面临的问题是我可能会多次添加监听器/绑定属性,这会造成内存泄漏。
这是我的意思的一个例子。
控制器:
public class Controller implements Initializable {
@FXML private TableView<Model> table;
@FXML private TableColumn<Model, String> column;
@FXML private Button change;
@Override
public void initialize(URL location, ResourceBundle resources) {
column.setCellValueFactory(data -> data.getValue().text);
column.setCellFactory(cell -> new ColoredTextCell());
Model apple = new Model("Apple", "#8db600");
table.getItems().add(apple);
table.getItems().add(new Model("Banana", "#ffe135"));
change.setOnAction(event -> apple.color.setValue("#ff0800"));
}
@Getter
private class Model {
StringProperty text;
StringProperty color;
private Model(String text, String color) {
this.text = new SimpleStringProperty(text);
this.color = new SimpleStringProperty(color);
}
}
private class ColoredTextCell extends TableCell<Model, String> {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || getTableRow() == null || getTableRow().getItem() == null) {
setGraphic(null);
return;
}
Model model = (Model) getTableRow().getItem();
Text text = new Text(item);
text.setFill(Color.web(model.getColor().getValue()));
// This way I add the listener evey item updateItem is called.
model.getColor().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
text.setFill(Color.web(newValue));
} else {
text.setFill(Color.BLACK);
}
});
setGraphic(text);
}
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Button?>
<AnchorPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="stackoverflow.tabpane.Controller">
<VBox>
<Button fx:id="change" text="Change color"/>
<TableView fx:id="table">
<columns>
<TableColumn fx:id="column" prefWidth="200"/>
</columns>
</TableView>
</VBox>
</AnchorPane>
由于单元格没有直接观察到颜色属性,因此如果它发生更改,则不会调用 updateItem,因此我必须以某种方式聆听。
我需要在 color 更改后触发updateItem。这将导致对侦听器内容的一次调用。
有什么方法可以在同一个单元格中监听模型的另一个变化,或者以某种方式调用更新项,以便呈现变化。
【问题讨论】:
标签: java javafx tableview javafx-8 listener