views:

23

answers:

1

I know this is kind of a beginners question but my books aren't explaining it and the API isn't helping much when I don't understand it. Someone please help me to get this.

I created a JList using NetBeans and everything is set to whatever NetBeans has as a default for JLists.

My goal is to make a JList show a List of [x] if a user picks "blah" out of a JComboBox.

I've gotten to use an ActionListener on the JComboBox but I'm not quite sure on how to add or remove items from a JList, so my question is:

In simple terms, how would I go about coding a way to add and remove from a JList?

Help is appreciated. Thanks :)

+1  A: 

Netbeans generates a JList with a simple model:

jList1.setModel(new javax.swing.AbstractListModel() {
    String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
    public int getSize() { return strings.length; }
    public Object getElementAt(int i) { return strings[i]; }
});

The values of this model cannot be changed afterwards.


You can either create a new model when you need to change the values, or declare your own model:

private DefaultListModel listModel = new DefaultListModel();

and change the model-property of your JList to Custom Code, and enter the name of your model (listModel), so that the generated code looks like this:

jList1.setModel(listModel);

jList1 [JList] - model

With this model you can then call add (or addElement) or one of the remove*-methods:

listModel.addElement("Test");

Make sure to read the Java Tutorial How to Use Lists for more information.

Peter Lang
thanks :D gonna try it out and see if it works...I seriously had no idea how to work with them :\
Kitsune
it worked! Thanks!!!!
Kitsune
@Kitsune About how models work. Here is a very good overview of Swing architecture: [A Swing Architecture Overview](http://java.sun.com/products/jfc/tsc/articles/architecture/)
Taisin