2016-08-27 3 views
0

특정 값이 TableView 인 일부 셀만 색을 지정하는 방법이 있습니까?Javafx 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()null 항목을 추가하면 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

관련 문제