Java 在 JFrame 中刷新 JList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4262669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:08:26  来源:igfitidea点击:

Refresh JList in a JFrame

javaswingjlist

提问by Skizit

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..

我有一个 JList,它显示来自向量的信息。然后用户可以从这个向量中添加和删除信息。从 Vector 添加/删除项目时,是否可以刷新 JFrame 中的 JList?目前我在做..

 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?

但这不会将 JList 刷新为任何新内容。我已经检查过,我的矢量内容等确实发生了变化,但列表并未刷新。为什么?我该如何解决?

采纳答案by camickr

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

您不应该更新 Vector。应直接对 ListModel 进行更改,然后该表将自动重新绘制自身。

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

如果由于 Vector 的更改而决定重新创建 ListModel,则可以通过执行以下操作来更新列表:

list.setModel( theNewModel );

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

编辑:忘记 Vector 并将数据直接加载到 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.

现在,无论何时需要更改数据,都可以直接使用 addElement()、removeElement() 或 set() 方法更新模型。该列表将自动重新绘制。

回答by Cousin Roy

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 图形“刷新”的解决方案。尝试在每次添加或删除 Jlist 持有的模型元素后调用此方法。

Jlist_name.ensureIndexIsVisible(model_name.getSize());

Jlist_name.ensureIndexIsVisible(model_name.getSize());

回答by gerardw

Call updateUIon the Jlist after modifying your Vector.

修改 Vector 后调用Jlist 上的updateUI

回答by Ikkesh Ramanna

you can use list.setListData(vector) each time the vector changes

每次向量更改时,您都可以使用 list.setListData(vector)