tags:

views:

152

answers:

2

I've been looking through the Java API, but have had no luck in working this out. After you initiate a JList, is there any way to replace, or reload the 'data' string? I've also been looking to do the same thing with a JComboBox.

String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
+1  A: 

The list data is stored in a ListModel (Accessable via the get/set Model methods). You simply need to create a new ListModel (Well, an implementation of a ListModel) and pass it to the JList using its setModel method.

Richie_W
How come it is set with a string initially then?
Aaron Moodie
+1  A: 

You are using one of the utility constructors for JList, which takes an array. The List is backed by a ListModel. The utility constructor uses the following to create an implementation of an AbstractListModel:

new AbstractListModel() {
            public int getSize() { return listData.length; }
            public Object getElementAt(int i) { return listData[i]; }
}

where listData would be your data set. You can do the same and pass it into dataList.setModel(). You might be best served, if this is for more than just a prototype, by creating your own, full-blown implementation of ListModel.

For reference, here is the JList tutorial from Sun.

JComboBox is a bit simpler, as the DefaultComboBoxModel class has a constructor that takes an array of Object as a parameter. To replace the data there, you can simply call:

 myComboBox.setModel(new DefaultComboBoxModel(data));
akf
thanks akf. That makes things a little clearer. I've been looking for how to replace the array ...
Aaron Moodie
Thanks akf, got it all working!
Aaron Moodie