Reputation: 429
I would like to know if there is a way to display a specific property for the items of a JList
when it is built from an ArrayList
.
I just want to choose the property that will be displayed in a list when I do this:
JList<String> elementsList = new JList(elementsArrayList.toArray());
elementsScrollPane.setViewportView(elementsList);
Thanks for any help or references you could give me!
Upvotes: 0
Views: 379
Reputation: 1090
1.
The simplest way is
first to scan your input elements list for the property you desire to show
String[] properties = elementsArrayList.stream().map(element::getStringProperty).toArray()
Then use it as an input model for your swing control new JList(properties)
define JList basing on the original objects you have (through ListModer or as is, by an array)
new JList(elementsArrayList)
and then create your ListCellRenderer class, which will display the property of interest as a lable and set this renderer to the list
jList.setCellRenderer(youCellRedererInstance)
Upvotes: 1
Reputation: 14999
You can set a ListCellRenderer
.
Essentially, you write a function
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected, boolean cellHasFocus)
which returns a Component
. To make things easier, you can extend DefaultListCellRenderer
and call it's implementation after you extracted the value you want to display from the list element, ie
{
if (value instanceof YourClass) {
YourClass ob = (YourClass) value;
return super.getListCellRendererComponent(list, ob.getProperty(), index, isSelected, cellHasFocus);
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
Then you set your renderer to your elementList
.
Upvotes: 2