2016-04-03 206 views
1

我有一個由幾個Label控件組成的自定義控件:日期,標題,文本等。控件有fxml文件和控制器。我想用這個控件作爲ListView的一個單元格。我創建了一個自定義的ListCell在JavaFx 8 listview單元格中的自定義控件fxml

public class NoteTextCell extends ListCell<Note>{ 
//.... 
    protected void updateItem(Note note, boolean isEmpty){ 
     if(isEmpty|| note == null){ 
     //.... 
     } 
     else { 
      FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/note.fxml")); 
      Node node = loader.load(); 
      setGraphic(node); 
     } 

    } 
} 

但我不知道它是做正確的方式。我的應用程序中的ListView可能有成千上萬的項目。在我對每個單元更新的理解中,它必須在創建圖形節點之前加載fxml,進行解析和其他操作。有沒有更好的方法來解決這個問題?

回答

2

裝入FXML每個單元一次,只是將其配置爲您在updateItem(...)方法需要:

public class NoteTextCell extends ListCell<Note>{ 

    private final Node graphic ; 
    private final NoteController controller ; 

    public NoteTextCell() throws IOException { 
     FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/note.fxml")); 
     graphic = loader.load(); 
     controller = loader.getController(); 
    } 

    @Override 
    protected void updateItem(Note note, boolean isEmpty){ 
     if(isEmpty|| note == null){ 
      setGraphic(null); 
     } 
     else { 
      // configure based on note: 
      controller.setText(...); 
      controller.setXXX(...); 
      setGraphic(graphic); 
     } 

    } 
} 

在這裏,我假設FXML文件聲明控制器類NoteController和你定義的方法其中您需要爲特定的Note配置UI。

這樣,FXML僅爲每個創建的單元格加載一次(不管列表中有多少項目,它可能不會超過20個),並且更新它的(相對有效的)方法是當用戶滾動或單元格以其他方式重用時根據需要調用。

相關問題