user1403668
user1403668

Reputation: 1

How to change element's view in JList after adding to ListModel?

How can i change element's view in JList after adding array(-s) to ListModel. Needed:

2.0 11.0 1.0

Having:

[D@198dfaf

I really don't want to use "array to string" conversion before adding and after getting from JList.. Is there any ideas? Thanks!

Upvotes: 0

Views: 499

Answers (2)

tenorsax
tenorsax

Reputation: 21233

As an alternative to changing renderer, or overriding toString() you can consider adding a view adapter for the objects you add to the list. Something similar to this simplified example:

class ArrayListViewAdapter {
    Object[] list;

    public ArrayListViewAdapter(Object[] list){
        this.list = list;
    }

    @Override
    public String toString(){
        return StringUtils.join(list, " ");
    }
}

Then to add items to the model:

model.addElement(new ArrayListViewAdapter(new Integer[]{1, 2, 3}));

Upvotes: 0

Guillaume Polet
Guillaume Polet

Reputation: 47637

You can use a ListCellRenderer for that purpose. It allows you to return a Component that represents the value you have put in the model of the JList.

The default CellRenderer is the DefaultListCellRenderer which is basically an extension of a JLabel and with all the proper look & feel settings already set. So you could extend DefaultListCellRenderer and set the array-text on the returned value.

Upvotes: 2

Related Questions