Change JList contents after it's already been displayed?
I have a JList I'm using in my frame;
This is how it is set up in the constructor of my class:
Code:
String tobesplit = "Item1;Item2;Item3";
String liststring[] = tobesplit.split(";");
listbox1 = new JList(liststring);
In this way, the JList displays Item1 for index 0, item2 for index 1, and so on.
What I'm trying to do is make it so that my JButton changes the contents of the JList.
For example, let's say I wanted the contents of my JList to change to the items of another string array called "newliststring".
Code:
else if (event.getSource() == button1){
listbox1 = new JList(newliststring);
}
No errors, but it doesn't do what I want... It doesn't seem to do anything at all.
What code would I use to change the contents of my JList once it's already been displayed?
Help is much appreciated, Thanks.
Re: Change JList contents after it's already been displayed?
What your code does is create a new JList with the new data, but it doesn't do anything to the JList that is displayed in the GUI. The key is that you must understand the difference between reference variables and objects. Your code above will change the object that your listbox1 variable refers to, but it does nothing to the object that is displayed, other than to have listbox1 not refer to it anymore.
Your best bet is to change the JList model (use a DefaultListModel) or the data held by the model (if changing a few items, not all items), not the JList itself.
Re: Change JList contents after it's already been displayed?
Thanks, works great!
Here's my final code:
Code:
listboxmodel1 = new DefaultListModel();
listbox1 = new JList(listboxmodel1);
Code:
else if (event.getSource() == button1){
load loadobject = new load();
listboxmodel1.removeAllElements();
String list[] = loadobject.loadfile().split(";");
int loop = 0;
while (loop < list.length){
listboxmodel1.addElement(list[loop]);
loop++;
}