28

I've got a JList which displays information from a vector. The user can then add and remove information from this vector. Is it possible to refresh the JList inside my JFrame when items are added / removed from the Vector? Currently I'm doing..

 list = new JList(names);
 jframe.add(new JScrollPane(list), BorderLayout.CENTER);

but this doesn't refresh the JList to anything new. I've check and my vector contents etc. do change but the list isn't refreshing. Why? how can I fix it?

Skizit
  • 43,506
  • 91
  • 209
  • 269
  • 3
    What class are you using as the JList's model? It's the job of the ListModel to notify when it has been updated, so that the JList can redraw itself when its underlying data changes. – Mike Clark Nov 24 '10 at 01:22
  • Mike, if you put that in an answer, I'd upvote it. – Amir Afghani Nov 24 '10 at 01:25

3 Answers3

38

You should not be updating the Vector. Changes should be made directly to the ListModel then the table will repaint itself automatically.

If you decide to recreate the ListModel because of the changes to the Vector, then you update the list by doing:

list.setModel( theNewModel );

Edit: Forget the Vector and load the data directly into the DefaultListModel:

DefaultListModel model = new DefaultListModel();
model.addElement( "one" );
model.addElement( "two" );
JList list = new JList( model );

Now whenever you need to change the data you update the model directly using the addElement(), removeElement() or set() methods. The list will automatically be repainted.

camickr
  • 321,443
  • 19
  • 166
  • 288
10

Call updateUI on the Jlist after modifying your Vector.

gerardw
  • 5,822
  • 46
  • 39
  • 1
    Not clear why a "You should not"-response is the accepted answer. This one works, when you have user defined List Element and ListCellRenderer and need to adapt the view for some muted attribute of a List Element. – Sam Ginrich Jan 29 '22 at 08:39
  • @SamGinrich this is utterly __wrong__ .. updateUI is for changing the componentUI, it's unrelated to the data – kleopatra Aug 23 '22 at 04:01
  • @kleoptra I use updateUI() for repainting, which is the topic. – Sam Ginrich Aug 23 '22 at 21:55
4

I think I found the solution for the Jlist's graphic 'refresh'. Try calling this method after each add or remove element of the model that is held by the Jlist.

Jlist_name.ensureIndexIsVisible(model_name.getSize());

Cousin Roy
  • 191
  • 1
  • 6
  • 2
    It's briliant solution. Helped me. – qmor Jun 27 '18 at 10:23
  • 1
    late comment, but this is an awesome answer! Calling JList.updateGui() will trigger some kind of repaint that can disturb the layout under some circumstances. That solution is way better:) – ItFreak Sep 06 '19 at 07:29