2016-09-29 39 views
0
TableColumn tc = new TableColumn(); 

tc.getStyleClass.add(".style in css file") 

我使用css文件設置了表格列。我想讓每個細胞都有不同的背景。有沒有辦法做到這一點?JavaFX Tableview使特定單元格變爲有色

TableColumn的第1行bakcground顏色=綠色,ROW2 =紅色,ROW3 =藍色....等

回答

5

你必須使用setRowFactory您的TableView和更改行樣式。 一個小例子有:

tableView.setRowFactory(new Callback<TableView<Data_type>, TableRow<Data_type>>(){ 
      //There can define some colors. 
      int color = 0; 
      String colors[] = new String[]{"red","blue","green"}; 
      @Override 
      public TableRow<Data_type> call(TableView<Data_type> param) { 
       final TableRow<Data_type> row = new TableRow<Data_type>() { 
        @Override 
        protected void updateItem(Data_type item, boolean empty) { 
         super.updateItem(item, empty); 
         //there write your code to stylize row 
         if(getIndex() > -1){ 
          String color = colors[getIndex() % 3]; 
          setStyle("-fx-background-color: "+ color + ";"); 

         } 
        } 
       }; 
       return row; 
      } 
     }); 

結果:
enter image description here

+1

臨尖:用'-fx-background'代替'-fx-背景color'。這將正確保留邊框,並允許文本顏色自動適應背景顏色的明暗。 –

+0

當我們滾動時,表視圖改變顏色 –

相關問題