Yashar
Yashar

Reputation: 2723

make list view show what I want JavaFX

I have created a class and added it to a observable list, I also have a list view which I set its item to my observable list.

Problem is when I add an object from my class to the observable list, list view shows their address on memory like package.TestClass@574f5892, How can I make list view to show the text stored in each object and their image instead of their memory address?

Thanks

Upvotes: 3

Views: 4125

Answers (1)

James_D
James_D

Reputation: 209340

A quick hack is just to define a toString method in your TestClass returning the text you want to display. This isn't really a robust solution, because in general you might want the toString() method to return something different from the text you want displayed in a GUI environment.

The "proper" way to do this is to set a cellFactory on the list view. Something along the lines of

listView.setCellFactory(lv -> new ListCell<TestClass>() {
    @Override
    public void updateItem(TestClass item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
        } else {
            String text = ... ; // get text from item
            setText(text);
        }
    }
});

To include an image, you can do

listView.setCellFactory(lv -> new ListCell<TestClass>() {

    private final ImageView imageView = new ImageView();
    @Override
    public void updateItem(TestClass item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            String text = ... ; // get text from item
            setText(text);
            Image image = ... ; // get image from item
            imageView.setImage(image);
            setGraphic(imageView);
        }
    }
});

Upvotes: 7

Related Questions