2

I would like to have example on how to update a JList when I add or remove elements from a ArrayList.

The ArrayList is part of Model class. The Model class is passed to the view (which is a JPanel containing several swing components, and the JList I want to update) via its constructor. The model class is also injected in a class that reads values received from the server. When i received data from the server I add some of them to my arrayList by doing model.getArrayList().add(data). When I add data to the arrayList i would like to update the JList in my view. I would like to have help on how to link my ArrayList with my JList.

jzd
  • 23,473
  • 9
  • 54
  • 76
wotan2009
  • 151
  • 1
  • 3
  • 6

2 Answers2

6

You need to use a ListModel to control adding and removing items from a JList. The tutorial is very useful: http://download.oracle.com/javase/tutorial/uiswing/components/list.html

Here is some example code from the tutorial:

listModel = new DefaultListModel();
listModel.addElement("Jane Doe");

listModel.insertElementAt(employeeName.getText(), index);    

int index = list.getSelectedIndex();
listModel.remove(index);

If you have an arraylist you could build your own List Model around it.

jzd
  • 23,473
  • 9
  • 54
  • 76
4

If you create your own ListModel you should extend AbstractListModel and when implementing your addElement method, you need to call a fire-method (for notifying the user interface for the update), like:

public void addElement(MyObject obj) {
    myArrayList.add(obj);
    fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
}

You custom ListModel should look something like this:

public class MyListModel extends AbstractListModel {

    private final ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();

    public void addElement(MyObject obj) {
        myArrayList.add(obj);
        fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
    }

    @Override
    public Object getElementAt(int index) { return myArrayList.get(index); }

    @Override
    public int getSize() { return myArrayList.size(); }
}
Jonas
  • 121,568
  • 97
  • 310
  • 388
  • Hello, so in the case i need to create the ListModel in my Model class, then i don't need a ArrayList. I could use the ListModel instead no ? – wotan2009 Jul 25 '11 at 13:04
  • @wotan: Your `Model` class should extend `AbstractListModel` and you need an `ArrayList` to have your elements in. It's more work if you want to use `ListModel` then you need to write the notifying by hand. – Jonas Jul 25 '11 at 13:05