【问题标题】:Trigger the update of a TableView's CellValue without changing the value在不更改值的情况下触发 TableView 单元格值的更新
【发布时间】:2015-01-06 11:22:59
【问题描述】:

每行包含三个具有 RGB 值的单元格。我使用这些 RGB 值来设置同一行中另一个单元格的背景。在需要为背景着色的单元格上,我有一个回调,可以获取 RGB 值并完美地设置背景。所以整个TableView 看起来完全符合我的需要。我有一个颜色选择器,这个选择器需要更新包含三个 RGB 值的选定行。我能够设置新的三个 RGB 值,但我还需要具有彩色背景的单元格将自身更新为新的 RGB 值。在下面的代码中,我找到了一种方法来做到这一点,但我相信这相当难看。

@FXML void handleColorPicker(ActionEvent event) 
{
    int r = (int) (comColorPicker.getValue().getRed()*255);
    int g = (int) (comColorPicker.getValue().getGreen()*255);
    int b = (int) (comColorPicker.getValue().getBlue()*255);

    ComTableView.getSelectionModel().getSelectedItem().setRCom(r);
    ComTableView.getSelectionModel().getSelectedItem().setGCom(g);
    ComTableView.getSelectionModel().getSelectedItem().setBCom(b);
    // we need to kick the cell value so it updates also the background color so we clear and rewrite the text string
    String currentName = ComTableView.getSelectionModel().getSelectedItem().getCommodityName();
    ComTableView.getSelectionModel().getSelectedItem().setCommodityName(" ");
    ComTableView.getSelectionModel().getSelectedItem().setCommodityName(currentName);
}   

上面代码的最后三行触发了单元格的updateItem,但我认为我这样做的方式很丑陋。我想知道,有没有更好的方法呢?

【问题讨论】:

    标签: java user-interface javafx tableview


    【解决方案1】:

    有两种方法:

    1. 使用 JavaFX property value extractors
    2. 部分重写您的数据类

    如果您沿路线 2 行驶: 让我们假设您在表中的数据类是 ColorData` 并且具有三个属性:

    • int RCom
    • int GCom
    • int BCom
    • String CommodityName

    现在,如果您将 CommodityNameString 更改为 StringProperty 并将其提供给 TableView 通过

    commodityNameColumn.setCellValueFactory(cellData -> cellData.getValue().commodityNameProperty());
    

    commodityNameColumn 是 TableView 的 TableColumn,它显示了 commodityNameProperty() 一个新方法 ColorData 提供对新 StringProperty 的访问权限。

    现在,如果您通过它的 setter 更改 StringProperty,并且值实际上发生了变化,TableCell 将相应地更新。


    如果仍然不清楚如何将数据类链接到 JavaFX TableView,我推荐this tutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多