2016-01-13 22 views
0

我必須使用ListView顯示5000個節點。每個節點都包含複雜的控件,但只有一些文本部分在節點中不同。我如何重複使用現有節點控件在滾動時重新創建我的單元格JavaFX虛擬化控件使用

+0

什麼是細胞?你在使用TableView嗎? – VGR

+1

如果只有文本不同,那麼'ListView'的數據類型應該是'String',列表視圖的'items'應該只包含5000個字符串。然後使用單元工廠來配置顯示器。除了沒有更多細節和代碼之外,很難回答你的問題:你可能想編輯你的問題來提供這個問題。 –

回答

0

James_D的答案指向了正確的方向。通常情況下,在JavaFX中,您不必擔心重複使用現有節點--JavaFX框架完全可以實現這一點,即開即用。如果你想實現一些自定義單元格呈現,你需要設置一個電池廠,這通常是這樣的:

listView.setCellFactory(new Callback() { 
    @Override 
    public Object call(Object param) { 
    return new ListCell<String>() { 

     // you may declare fields for some more nodes here 
     // and initialize them in an anonymous constructor 

     @Override 
     protected void updateItem(String item, boolean empty) { 
     super.updateItem(item, empty); // Default behaviour: zebra pattern etc. 

     if (empty || item == null) { // Default technique: take care of empty rows!!! 
      this.setText(null); 

     } else { 
      this.setText("this is the content: " + item); 
      // ... do your custom rendering! 
     } 
     } 

    }; 
    } 
}); 

請注意:這應該工作,但僅是說明性的 - 我們的Java離散事件知道,如,我們會使用StringBuilder進行字符串連接,特別是在代碼經常執行的情況下。 如果你想要一些複雜的渲染,你可以使用額外的節點構建該圖形,並使用setGraphic()將它們設置爲圖形屬性。這與Label控件類似:

// another illustrative cell renderer: 
listView.setCellFactory(new Callback() { 
    @Override 
    public Object call(Object param) { 
    return new ListCell<Integer>() { 

     Label l = new Label("X"); 

     @Override 
     protected void updateItem(Integer item, boolean empty) { 
     super.updateItem(item, empty); 

     if (empty || item == null) { 
      this.setGraphic(null); 

     } else { 
      this.setGraphic(l); 
      l.setBackground(
        new Background(
          new BackgroundFill(
            Color.rgb(3 * item, 2 * item, item), 
            CornerRadii.EMPTY, 
            Insets.EMPTY))); 
      l.setPrefHeight(item); 
      l.setMinHeight(item); 
     } 
     } 

    }; 
    } 
}); 
+0

在第二代碼中,我們創建和刪除標籤控件,只要我們滾動或項目的變化,有沒有一種方法,我們可以緩存這個控制重用? –