2017-06-18 17 views
0

我想了解如何使用JavaFX,但很難理解如何爲不同顏色的tableView的不同行着色。如何上色一行TableView?

我有一個場景,根據單選按鈕獲取不同的數據。一個選項顯示沒有顏色的數據,另一個選項取決於數字的大小。

有缺陷的方法:

private void drawTableColor(){ 

    //tableColumns[0] = new TableColumn("Spieltag"); 

    //tableColumns[0].setCellValueFactory(new PropertyValueFactory<MyClass, String>("day")); 

    /*tableColumns[0].setCellFactory(column -> { 
     return new TableCell<MyClass,String>(){ 
      @Override 
      protected void updateItem(String s, boolean empty){ 
       super.updateItem(s, empty); 

       int i = Integer.parseInt(s); 
       System.out.println("TEST " +i); 
       if (i<=3){ 
        setTextFill(Color.BLUE); 
       } else if (i==4){ 
        setTextFill(Color.AZURE); 
       } else if (i <= 6){ 
        setTextFill(Color.GREEN); 
       } else if (i == 16){ 
        setTextFill(Color.ORANGE); 
       } else if (i>16){ 
        setTextFill(Color.RED); 
       } 
      } 

     }; 
    });*/ 

    ObservableList<MyClass> data2 = FXCollections.observableArrayList(data); 
    tableView.setItems(null); 
    tableView.setItems(data2); 
} 

的出注釋部分是給我找麻煩。它不會爲該行着色,也不會在此列中顯示任何內容。如果第一行被註釋掉,它將跳過updateItem部分。 任何想法我做錯了什麼?

+0

你肯定是錯過'的setText(S)'在'updateItem'方法的風格,你需要(至少)在嘗試執行'Integer.parseInt(s)'之前檢查單元格是否爲空(否則最終會嘗試解析空值)。如果仍然不起作用,您需要發佈'MyClass'的代碼 –

+0

謝謝,這幫助我填補了專欄。 –

回答

1

問題是你用settextfill() 相反,你應該設置背景

private void drawTableColor(){ 

    //tableColumns[0] = new TableColumn("Spieltag"); 

    //tableColumns[0].setCellValueFactory(new PropertyValueFactory<MyClass, String>("day")); 

    /*tableColumns[0].setCellFactory(column -> { 
     return new TableCell<MyClass,String>(){ 
      @Override 
      protected void updateItem(String s, boolean empty){ 
       super.updateItem(s, empty); 

       int i = Integer.parseInt(s); 
       System.out.println("TEST " +i); 
       if (i<=3){ 
        setStyle("-fx-background-color: blue"); 
       } else if (i==4){ 
        setStyle("-fx-background-color: azure"); 
       } else if (i <= 6){ 
        setStyle("-fx-background-color: green"); 
       } else if (i == 16){ 
        setStyle("-fx-background-color: orange"); 
       } else if (i>16){ 
        setStyle("-fx-background-color: red"); 
       } 
      } 

     }; 
    });*/ 

    ObservableList<MyClass> data2 = FXCollections.observableArrayList(data); 
    tableView.setItems(null); 
    tableView.setItems(data2); 
}