4

Is there anyway to add an image to a JavaFX ListView?

This is how I am currently setting the list view items.

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

I'm also using the list view value as an id to know which was selected.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ricktza
  • 43
  • 1
  • 5

2 Answers2

3

Implement a ListCell that displays the image and set a cellFactory on the ListView. The standard oracle tutorial has an example of a custom list cell implementation.

You would do something along the following lines:

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);
        }
    }
});

The updateItem(...) method can be called quite often, so it is probably better to preload the images and make them available to the cell, rather than creating them every time updateItem(...) is called.

James_D
  • 201,275
  • 16
  • 291
  • 322
  • Thanks, i'm fairly new to JavaFX and i was struggling to work out how the cell factory worked. This code works flawlessly :D – Ricktza Aug 29 '14 at 16:20
0

remember to refresh or load your Listview with 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
    }
diego matos - keke
  • 2,099
  • 1
  • 20
  • 11