在不更改值的情况下触发TableView单元格值的更新

时间:2014-11-10 07:46:53

标签: java user-interface javafx tableview

每行包含三个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,但我想我是以丑陋的方式做这件事。我想知道,有没有更好的方法呢?

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点:

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

  3. 如果您要沿着路线2前进: 让我们假设表中的数据类是ColorData`并具有三个属性:

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

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

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

    其中commodityNameColumn是TableView的TableColumn,显示commodityNameProperty() ColorData的新方法,可以访问新的StringProperty。

    现在,如果您通过其setter更改StringProperty,并且值实际更改,则TableCell将相应地更新。


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

相关问题