2014-08-29 80 views
3

無論如何要將圖像添加到JavaFX ListView?JavaFX ListView中的圖像

這是我目前如何設置列表視圖項目。

private ListView<String> friends; 
private ObservableList<String> items; 
items = FXCollections.observableArrayList(getFriends); 
friends.setItems(items); 

我也使用列表視圖值作爲id來知道哪個被選中。

回答

3

執行顯示圖像的ListCell並在ListView上設置cellFactorystandard oracle tutorial有一個自定義列表單元實現的例子。

你會做大意如下的內容:

friends.setCellFactory(listView -> new ListCell<String>() { 
    private ImageView imageView = new ImageView(); 
    @Override 
    public void updateItem(String friend, boolean empty) { 
     super.updateItem(friend, empty); 
     if (empty) { 
      setText(null); 
      setGraphic(null); 
     } else { 
      Image image = getImageForFriend(friend); 
      imageView.setImage(image); 
      setText(friend); 
      setGraphic(imageView); 
     } 
    } 
}); 

updateItem(...)方法可以經常調用,因此它可能是更好的預載的圖片,並將其提供給細胞,而不是創建它們每次調用updateItem(...)

+0

謝謝,我相當新的JavaFX,我一直在努力工作,如何細胞工廠工作。 此代碼完美地工作:D – Ricktza 2014-08-29 16:20:50

0

記得刷新或加載您的列表視圖 與myListViewWithPath.setItems(myObserverFilledWithImages);

@FXML 
    private void browseButton(ActionEvent event) throws Exception { 
     System.out.println("browseButton"); 
     DirectoryChooser chooser = new DirectoryChooser(); 
     File file = chooser.showDialog(myStage); 
     file = new File("E:\\FOLDER\\Imagen_File"); 

     if (file != null) { 
      directoryField.setText(file.toString()); 
      oImage.setAll(load(file.toPath())); 
     } 
     imageFilesList.setItems(oImage); //this one load or refresh the ListView 
    }