Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh JList in a JFrame

Tags:

java

swing

jlist

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?

like image 609
Skizit Avatar asked Nov 24 '10 01:11

Skizit


People also ask

How do you refresh a JList?

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.

What is JList in Java Swing?

JList is part of Java Swing package . JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class.

How do I remove an item from JList?

To actually remove the item, we use the syntax . remove(int); where the integer is the index of the item you wish to remove. That is how we add and remove things from a JList, and this concludes our tutorial on the JList.

Is JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.


2 Answers

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.

like image 126
camickr Avatar answered Oct 10 '22 04:10

camickr


Call updateUI on the Jlist after modifying your Vector.

like image 10
gerardw Avatar answered Oct 10 '22 02:10

gerardw