2016-12-25 57 views
3

列表視圖setCellFactory我嘗試做內ListView創建一個定製的項目,讓我們說這是標籤,我想執行setCellFactory,而我使用Label我沒有看到該項目(標籤的文字),爲什麼?與普通標籤

ListView<Label> list = new ListView<Label>(); 
ObservableList<Label> data = FXCollections.observableArrayList(
     new Label("123"), new Label("45678999")); 

@Override 
public void start(Stage stage) { 
    VBox box = new VBox(); 
    Scene scene = new Scene(box, 200, 200); 
    stage.setScene(scene); 
    stage.setTitle("ListViewExample"); 
    box.getChildren().addAll(list); 
    VBox.setVgrow(list, Priority.ALWAYS); 

    list.setItems(data); 

    list.setCellFactory(new Callback<ListView<Label>, ListCell<Label>>() { 


      @Override 
      public ListCell<Label> call(ListView<Label> list) { 
       ListCell<Label> cell = new ListCell<Label>() { 
        @Override 
        public void updateItem(Label item, boolean empty) { 
         super.updateItem(item, empty); 
         if (item != null) { 
          setItem(item); 
         } 
        } 
       }; 

       return cell; 
      } 
     } 
    ); 

    stage.show(); 
} 

回答

2

如果你想顯示擴展Node沒有必要使用自定義ListCell的項目進行。默認工廠的ListCell已經這樣做了。

不過你的情況,你打電話setItem代替setGraphic,你也不要設置該屬性回null,當細胞變空:

list.setCellFactory(new Callback<ListView<Label>, ListCell<Label>>() { 

    @Override 
    public ListCell<Label> call(ListView<Label> list) { 
     ListCell<Label> cell = new ListCell<Label>() { 
      @Override 
      public void updateItem(Label item, boolean empty) { 
       super.updateItem(item, empty); 
       // also sets to graphic to null when the cell becomes empty 
       setGraphic(item); 
      } 
     }; 

     return cell; 
    } 
}); 
+0

謝謝:)我錯過setGraphic –