2015-03-03 55 views
0

我目前正在使用TableView元素來開發一個小型學習項目。我根據其內容一樣,量變到質變的每一行的背景顏色:JavaFx Tableview,如何添加偵聽器並在同一工廠覆蓋updateItem

TableView.setRowFactory((row) -> new TableRow<Person>() { 

@Override 
public void updateItem(Person person, boolean empty) { 
    super.updateItem(person, empty); 

    switch (person.getPersonStatus()) { 
     case ST: 
     setStyle("-fx-control-inner-background: " + StatusColor.B_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;"); 
     break; 
     case CD: 
     setStyle("-fx-control-inner-background: " + StatusColor.D_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;"); 
     break; 
    } 
} 

我還希望得到對象的引用該行中,當我在該行雙擊。我用這個代碼:

TableView.setRowFactory((row) -> { 
    TableRow<Person> row = new TableRow<>(); 
    row.setOnMouseClicked(event -> { 
    if (event.getClickCount() == 2 && (!row.isEmpty())) { 
     Person rowData = row.getItem(); 
     System.out.println(rowData); 
    } 
    }); 
    return row; 
}); 

但這不起作用(我假設,因爲我分配兩個因子相互覆蓋)。有人可以幫我把兩個代碼示例合併成一個工作嗎?如何在工廠中重寫函數(updateItem)並同時附加一個監聽器?

問候

回答

0

只需將監聽器添加到您的第一個代碼塊創建TableRow

TableView.setRowFactory((tv) -> { 
    TableRow<Row> row = new TableRow<Person>() { 

     @Override 
     public void updateItem(Person person, boolean empty) { 
      super.updateItem(person, empty); 

      switch (person.getPersonStatus()) { 
       case ST: 
       setStyle("-fx-control-inner-background: " + StatusColor.B_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;"); 
       break; 
       case CD: 
       setStyle("-fx-control-inner-background: " + StatusColor.D_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;"); 
       break; 
      } 
     } 
    }; 
    row.setOnMouseClicked(event -> { 
     if (event.getClickCount() == 2 && (!row.isEmpty())) { 
      Person rowData = row.getItem(); 
      System.out.println(rowData); 
     } 
    }); 
    return row; 
}); 
+0

感謝您的快速答覆! – VictorRomeo 2015-03-04 10:25:59

相關問題