gpt4 book ai didi

JavaFX - 组合两个 CellFactory - TextFieldTableCell.forTableColumn() 和自定义一个

转载 作者:行者123 更新时间:2023-12-02 01:21:02 24 4
gpt4 key购买 nike

我有一个表列:

TableColumn<Foo, String> colStatus = new TableColumn("Status");
colStatus.setCellValueFactory(new PropertyValueFactory<>("statusElement"));

在此表上,我想应用此 cellFactory TextFieldTableCell.forTableColumn() ,这将使单元格可编辑。

但我也想将其与自定义 cellFactory 结合起来:

colStatus.setCellFactory(new Callback<>() {

public TableCell<Foo, String> call(TableColumn param) {

return new TableCell<>() {

@Override
public void updateItem(String item, boolean empty) {

super.updateItem(item, empty);

if (!isEmpty()){

if(item.equals("error")){

this.setTextFill(Color.RED);
setText(item);

}else{

this.setTextFill(Color.Black);
setText(item);

}

}

}
};
}

});

此单元格工厂根据单元格值设置单元格的文本颜色。

但我不知道如何使单元格可编辑,而且还根据值自定义其颜色。

这是 MCVE:

@Override
public void start(Stage primaryStage){

List<String> test = new ArrayList<>();
test.add("done(green)");
test.add("done(green)");
test.add("fail(red)");
test.add("done(green)");

TableView<String> tableView = new TableView<>();
tableView.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
tableView.setEditable(true);

TableColumn<String, String> col = new TableColumn<>("Column");
col.setCellValueFactory(data -> new SimpleStringProperty(data.getValue()));
col.setCellFactory(TextFieldTableCell.forTableColumn());
//I want to apply a color based by value from cell

tableView.getColumns().add(col);

tableView.setItems(FXCollections.observableArrayList(test));

primaryStage.setScene(new Scene(tableView));

primaryStage.show();

}

最佳答案

我终于发现我可以使用 TextFieldTableCell.forTableColumn() 进行自定义。

只需覆盖TextFieldTableCell

private static class CustomCell extends TextFieldTableCell<String, String>{

@Override
public void updateItem(String item, boolean empty){

super.updateItem(item, empty);

if(item == null || empty) {
setText(null);
return;
}

if(!isEmpty()){

if(item.equals("error")){

this.setTextFill(Color.RED);
setText(item);

}else{

this.setTextFill(Color.BLACK);
setText(item);

}

}

}

}

我固定的想法是 setCellFactoryCallBack 作为参数。

所以我尝试了很多方法来获取返回 TableCellCallBack

在我看到@Sedrick的回答后。

我发现我可以发送 lambda 实现,例如:setCellFactory(e -> new CustomCell())

感谢@Sedrick 和@kleopatra。

关于JavaFX - 组合两个 CellFactory - TextFieldTableCell.forTableColumn() 和自定义一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57677244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com