Image in JavaFX ListView

Can I add an image to a JavaFX ListView?

This is how I set the list items now.

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

I also use the list view value as an identifier to find out which one is selected.

+3
source share
2 answers

Embed ListCell, which displays the image and sets cellFactoryto ListView. The standard oracle tutorial contains an example implementation of a custom list.

You would do something in 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);
        }
    }
});

updateItem(...) , , , , , updateItem(...).

+3

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
    }
0

Source: https://habr.com/ru/post/1614924/


All Articles