2016-08-27 27 views
0

特定の値のセルを一部の色に塗りつぶす方法はありますか?TableViewJavafx Tableview特定の値を持つセルを色付けする方法

Callback<TableColumn, TableCell> historyTableCellFactory 
    = new Callback<TableColumn, TableCell>() { 
     public TableCell call(TableColumn p) { 
      TableCell newCell = new TableCell<CustomerHistoryStructure, String>() { 
       private Text newText; 

       @Override 
       public void updateItem(String items, boolean empty) { 
        super.updateItem(items, empty); 

        if (!isEmpty()) { 
         newText = new Text(items.toString()); 
         newText.setWrappingWidth(140); 
         this.setStyle("-fx-background-color:#e50000 ;"); 
         setGraphic(newText); 
        } 
       } 

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

上記のコードの問題は、プログラムが実行されていると私はTableViewにスクロールすると、他の細胞が自分で色付けしてしまうことがあります。

答えて

1

このコードの問題は、アイテムが追加されたときに行われた変更を元に戻すことがないことです。 graphicを削除することはありません。セルが空になり、特定の値が決してチェックされない場合でも、さらに、アイテムを追加すると、items.toString()はNPEにつながる可能性があります。また、Text要素を再作成する必要はありません。また、アイテムを特定の値と比較することもありません。

final String specificValue = ... 

new TableCell<CustomerHistoryStructure, String>() { 
    private final Text newText; 

    { 
     newText = new Text(); 
     newText.setWrappingWidth(140); 
    } 

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

     if (empty) { 
      setGraphic(null); 
      setStyle(""); 
     } else { 
      newText.setText(getString()); 
      setGraphic(newText); 

      // adjust style depending on equality of item and specificValue 
      setStyle(Objects.equals(item, specificValue) ? "-fx-background-color:#e50000 ;" : ""); 
     } 
    } 

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

私は2週間以上それを解決しようとしていました – Peter

関連する問題