OK so I have a JList and the content is provided with an array. I know how to add elements to an array but I want to know how to refresh a JList... or is it even possible? I tried Google. :\
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class bs extends JApplet implements MouseListener {
public static String newline;
public static JList list;
public void init() {
String[] data = {"one", "two", "three", "four"};
list = new JList(data);
this.getContentPane().add(list);
list.addMouseListener(this);
String newline = "\n";
list.setVisible(true);
}
public void refresh(){
Address found;
this.listModel.clear();
int numItems = this.getAddressBookSize();
String[] a = new String[numItems];
for (int i=0;i<numItems;i++){
found = (Address)Addresses.get(i);
a[i] = found.getName();
}
/* attempt to sort the array */
Arrays.sort(a, String.CASE_INSENSITIVE_ORDER);
for (int i=0;i<numItems;i++) {
this.listModel.addElement(a[i]);
}
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {
Object index = list.getSelectedValue();
System.out.println("You clicked on: " + index);
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void paint(Graphics g) {
}
}
Any ideas?
Thank you.
One good approach is to create a ListModel to manage the data for you and handle updates.
Something like:
DefaultListModel listModel=new DefaultListModel();
for (int i=0; i<data.length; i++) {
listModel.addElement(data[i]);
}
list=new JList(listModel);
Then you can simply make changes via the list model e.g.
listModel.addElement("New item");
listModel.removeElementAt(1); // remove the element at position 1