Ahmed
Ahmed

Reputation: 3458

Binding a Swing JList into an array

I want to bind a JList in a JScrollPane to an array , whenever the array changes the List changes .

Upvotes: 1

Views: 1747

Answers (1)

Andreas Krueger
Andreas Krueger

Reputation: 1507

The first idea, of course, would by to use one of JList's constructors and hope that the JList component is updated synchronously with the array:

public JList(Object[] listData);
public JList(Vector<?> listData);

Obviously, this does not work out. Only, if you use the third non-default constructor

public JList(ListModel model);

and use the default implementation DefaultListModel and update its elements directly by e.g.

DefaultListModel model = new DefaultListModel();
...
model.setElementAt(value, 25);

you receive a dynamically updated JList component, by updating the DefaultListModel.

What Java SE provides is a "fixed-size List backed up the specified array" by the java.util.Arrays.asList(T... a) method, compare Java SE API.

However, here the support of Java SE breaks. There is no ListModel implementation that is "backed-up by a List".

I have tried both ways to overcome this:

  1. implement the List interface in a class synchronously updating an underlying DefaultListModel
  2. extend DefaultListModel, synchronously updating an underlying List instance.

Neither way worked.

Therefore, I venture to say that Java SE does not support this feature yet. You have to code your own implementation of JList synchronized by a List instance or wait until a new Java distribution comes along, which features JList's or DefaultListModel's backed up by List instances.

Upvotes: 1

Related Questions