2016-08-03 79 views
0

我想在tableview的单元格的值为空时更改tableview的单元格背景色。你可以帮帮我吗?谢谢。 下面,我的源代码的概述,但它不起作用。如何动态地改变tableview的单元格背景

public class Cell extends TextFieldTableCell<Itemtest, String>{ 

    public Cell(StringConverter<String> str){ 
     super(str); 
     this.itemProperty().addListener((obs, oldValue, newValue)->{ 
        if(newValue.isEmpty()) 
         this.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY))); 
     }); 
    } 

    @Override 
    public void updateItem(String item, boolean empty) { 
     super.updateItem(item, empty); 
     setText(empty ? null : getString()); 
     setGraphic(null);   
    } 

    private String getString(){ 
     return getItem() == null ? "" : getItem().toString(); 
    } 

} 
+0

您不需要为此执行单元实施;你可以完全用CSS做 –

回答

0

与您的代码,你的背景设置为一种颜色,如果该项目成为""。万一项目应该改变,你永远不会改变它。此外,项目是""意味着该单元格是不是空的

此外,您已覆盖updateItem方法,该方法在项目更改或单元格变空时调用,应该用它来更新背景。

public class Cell extends TextFieldTableCell<Itemtest, String>{ 

    public Cell(StringConverter<String> str){ 
     super(str); 
    } 

    @Override 
    public void updateItem(String item, boolean empty) { 
     super.updateItem(item, empty); 
     setText(empty ? null : getString()); 
     setGraphic(null); 

     // is this really the check you want? 
     if (item != null && item.isEmpty()) { 
      this.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY))); 
     } else { 
      // change back to empty background 
      this.setBackground(Background.EMPTY); 
     } 
    } 

    private String getString(){ 
     return getItem() == null ? "" : getItem().toString(); 
    } 

} 
+0

当我点击一个按钮时(例如,确保值是数字或不是空的),我想对表格单元格的值进行一些控制,并更改它们单元格的背景颜色if这些限制不受尊重。我怎样才能做到这一点? – Rodja

+0

是否所有'TableCell'都检查'updateItem'?从JavaFX 8更新60开始,您可以使用'TableView.refresh()'。 – fabian

+0

我在'controlButton.setOnAction(ev - > {..})里面使用'TableView.refresh()';'它工作。非常感谢。 – Rodja