Getting back data from JList
Asked Answered
C

3

9

I was googling for a solution to retrieve data back from a JList component, but didn't find any.So, is there a method of Jlist that return its items? I don't want just a selected one. I want the whole list.

The reason is I have this method that updates all the components of a dialogbox base on the selected value of a list box. I want to update that list box from the same method. So to do that, the method should not update the list box whenever it gets called. It should compare the values in the list box with the most recent data that I store in one class.(goes into infinite loop otherwise) Only when data in the list box doesn't match with the data in the class, it gets updated.

Is there such method to retrieve all the data of list box?

Clementclementas answered 22/3, 2013 at 10:59 Comment(0)
S
13

You have to use the getModel() method to get the model data and then use the methods inside ListModel in order to get all the data elements.

ListModel model = list.getModel();

for(int i=0; i < model.getSize(); i++){
     Object o =  model.getElementAt(i);  
}

http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html#getModel()

http://docs.oracle.com/javase/6/docs/api/javax/swing/ListModel.html

Secondclass answered 22/3, 2013 at 11:2 Comment(1)
Thanks, that's what Im looking for!Clementclementas
D
4

To get the selections, you will need to use a combination of getModel and getSelectedIndices

ListModel model = jListInstance.getModel();

for(int index : jListInstance.getSelectedIndices()) {
    System.out.println(model.getElementAt(index));
}
Devorahdevore answered 22/3, 2013 at 11:7 Comment(1)
OP wants to get all the data and not just the selected elements only.Secondclass
R
1

Use the getModel() method to retrieve the data model that is contained within the JList. The List model can be traversed in the following manner:

ListModel list = jListObj.getModel();
for(int i = 0; i < list.getSize(); i++){
     Object obj = list.getElemenetAt(i);
}

http://docs.oracle.com/javase/6/docs/api/javax/swing/ListModel.html http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html#getModel%28%29

Rubrician answered 22/3, 2013 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.