Image in JavaFX ListView

前端 未结 2 1405
春和景丽
春和景丽 2021-01-14 15:28

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

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

private ListView friends;         


        
2条回答
  •  渐次进展
    2021-01-14 16:21

    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() {
        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.

提交回复
热议问题