首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaFX着色TableCell

JavaFX着色TableCell
EN

Stack Overflow用户
提问于 2016-01-28 08:18:44
回答 1查看 2.2K关注 0票数 5

我需要你的帮助!

我有一张有行的表格(名字等)现在,当放置在该行上的对象具有特定值时,我希望为特定的tableCells背景着色。但我只知道这个细胞的价值。但是我需要读取对象(在我的代码中称为TableListObject),才能知道我需要对单元格进行颜色化。但该“颜色值”在该行中不可见(没有列)。

这是我的代码:

代码语言:javascript
复制
for(TableColumn tc:tView.getColumns()) {
    if(tc.getId().equals("text")) {
        tc.setCellValueFactory(newPropertyValueFactory<TableListObject,String>("text"));
        // here i need to check the Objects value and coloring that cell
    }
}

这里有一个HTML来可视化我的问题:https://jsfiddle.net/02ho4p6e/

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-28 09:42:08

为所需的列调用单元格工厂,并重写updateItem方法。您需要检查它是否为空,如果不是,则可以进行对象检查,然后可以设置单元格背景的颜色或任何其他样式。希望这能有所帮助。

代码语言:javascript
复制
    tc.setCellFactory(column -> {
        return new TableCell<TableListObject, String>() {
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);
                    setStyle("");
                } else {
                    if (item.equals("Something")) {
                        setStyle("-fx-background-color: blue");
                    } else {
                        setStyle("");
                    }
                }
            }
        };
    });

编辑1:

如果要使用同一行中另一个单元格的值,请执行以下操作。您必须使用行的索引,并获得检查所需的项。

代码语言:javascript
复制
tc.setCellFactory(column - > {
   return new TableCell < TableListObject, String > () {
     protected void updateItem(String item, boolean empty) {
       super.updateItem(item, empty);

       if (item == null || empty) {
         setText(null);
         setStyle("");
       } else {
         int rowIndex = getTableRow().getIndex();
         String valueInSecondaryCell = getTableView().getItems().get(rowIndex).getMethod();
         if (valueInSecondaryCell.equals("Something Else")) {
           setStyle("-fx-background-color: yellow"); //Set the style in the first cell based on the value of the second cell
         } else {
           setStyle("");
         }

       }
     }
   };
 });

编辑2:

根据建议改进答案。这使用引用的对象。

代码语言:javascript
复制
   else {
         TableListObject listObject = (TableListObject) getTableRow().getItem();
         if (listObject.getMethod().equals("Something Else")) {
           setStyle("-fx-background-color: yellow"); //Set the style in the first cell based on the value of the second cell
         } else {
           setStyle("");
         }
       }
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35056108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档