2014-11-04 76 views
1

定製TreeCells我想代表TreeCell這樣的:使用電池工廠

http://i.imgur.com/wv00CEi.png

我試圖在細胞工廠讀書了,我知道我要使用此功能。但是我怎樣才能將圖形設置爲像所有TreeCell一樣?該圖像作爲HBox存儲在.fxml文件中。

非常感謝你:)

P.S.不一定在這裏找答案中的代碼,更多的是關於如何做到這一點或爲什麼不起作用的一般性解釋。

這是我試過的代碼。 fxml文件與文件位於同一個文件夾中。

這是錯誤代碼我得到:螺紋

例外「的JavaFX應用程序線程」顯示java.lang.NullPointerException:需要位置。

@Override 
public void updateItem(String item, boolean empty) { 
    super.updateItem(item, empty); 
    try { 
     this.hBox = (HBox) FXMLLoader.load(getClass().getResource("/Views/TreeCell.fxml")); 
    } catch (IOException e) { 
     System.out.println("This didn't work"); 
     e.printStackTrace(); 
    } 
    if (item != null) { 
     setGraphic(this.hBox); 
    } else { 
     setGraphic(null); 
    } 
} 
+0

你能告訴你已經嘗試的代碼?很難說沒有看到它,爲什麼它不起作用。 – 2014-11-04 15:34:15

+0

編輯顯示我正在嘗試的代碼片段。 – AnagramOfJoans 2014-11-04 15:54:59

回答

2

您收到的異常僅表示FXMLLoader找不到您指定的FXML文件。如果FXML文件是在同一個封裝與當前類,你應該能夠使用

this.hBox = (HBox) FXMLLoader.load(getClass().getResource("TreeCell.fxml")); 

如果你開始領先/資源路徑,它將被解釋爲相類路徑。

使用您顯示的代碼,性能可能會很差。使用單元工廠時,單元格創建相對較少,但它們的方法可能會相當頻繁地調用(特別是在快速滾動期間,或者在擴展和摺疊樹節點時)。用這種方法讀取和解析FXML文件可能是一個壞主意。

相反,你可以一次讀取文件創建單元格時,然後就重用在updateItem()方法所產生的HBox

tree.setCellFactory(treeView -> { 
    HBox hbox ; 
    try { 
     hbox = (HBox) FXMLLoader.load(getClass().getResource("TreeCell.fxml")); 
    } catch (Exception exc) { 
     throw new RuntimeException(exc) ; 
    } 
    return new TreeCell<String>() { 
     @Override 
     public void updateItem(String item, boolean empty) { 
      super.updateItem(item, empty); 
      if (item == null) { 
       setGraphic(null); 
      } else { 
       // configure graphic with cell data etc... 
       setGraphic(hbox); 
      } 
     } 
    }; 
}); 
+0

謝謝。這是文件路徑有問題。感謝提高運行速度的建議。我將代碼更改爲您發佈的內容,將FXML加載到我的CustomTreeCell構造函數中。 – AnagramOfJoans 2014-11-05 08:58:09