Add item to JList
Posted on 2006-11-09
As I'm learning Java, I'm having a little difficulty with the JList control. I'd like to know how to add/remove items dynamically at runtime, and have seen this example posted:
// create a model
DefaultListModel items = new DefaultListModel();
// create JList
JList list = new JList(items);
// add/remove items
items.add(0, "Item 1") // inserts into first position
items.addElement("Last Item"); // adds to end of list
items.remove(0); // remove first item
items.removeAllElements() // remove everything
However, my existing JList control that is already on the form is called jList1, and I'm curious how I'd make this above code work with my existing jList control. My first problem is I have to change DefaultListModel to javax.swing.DefaultListModel in order for it to compile, and I'm not sure where I'm allowed to place the preceeding example code (I'm wanting to place it in my button's click event).
Thanks for any help!