Java - 更改对象后更新 JList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9865119/
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
Java - Updating JList after changing an object
提问by mino
I have a JList which uses a DefaultListModel.
我有一个使用 DefaultListModel 的 JList。
I then add values to the model which then appear in the JList. I have created a MouseListener which (when double clicked) allows the user to edit the current user number of that person they have selected.
然后我将值添加到模型中,然后出现在 JList 中。我创建了一个 MouseListener ,它(双击时)允许用户编辑他们选择的那个人的当前用户号。
I have checked that the actual object of that record is being changed, and it is. The only issue I'm having is getting the actual Jlist to update to show the new values of that object.
我已经检查过该记录的实际对象是否正在更改,确实如此。我遇到的唯一问题是让实际的 Jlist 更新以显示该对象的新值。
Snippets of the current code I have are:
我拥有的当前代码的片段是:
Creating the JList and DefaultTableModel:
创建 JList 和 DefaultTableModel:
m = new DefaultListModel();
m.addListDataListener(this);
jl = new JList(m);
jl.addMouseListener(this);
Updating the object:
更新对象:
String sEditedNumber = JOptionPane.showInputDialog(this, "Edit number for " + name, number);
if (sEditedNumber != null) {
directory.update (name, sEditedNumber);
}
And (when jl is the JList and m is the DefaultTableModel):
并且(当 jl 是 JList 并且 m 是 DefaultTableModel 时):
public void contentsChanged(ListDataEvent arg0) {
jl.setModel(m);
}
采纳答案by Jason S
You need to call fireContentsChanged()
on the ListModel.
您需要调用fireContentsChanged()
ListModel。
回答by trashgod
Instead of setModel()
, update your existing model using one of the DefaultListModel
methods such as setElementAt()
, which will fireContentsChanged()
for you.
相反的setModel()
,使用的一个更新现有模型DefaultListModel
的方法,例如setElementAt()
,它会fireContentsChanged()
为你。
回答by user3669782
You need to call DefaultListModel.fireContentsChanged()
. But since this method is protected (I really wonder why), you can't do that directly. Instead, make a small subclass:
你需要打电话DefaultListModel.fireContentsChanged()
。但是由于这个方法是受保护的(我真的很想知道为什么),你不能直接这样做。相反,创建一个小的子类:
class MinoListModel<T> extends DefaultListModel<T>
{
public void update(int index)
{
fireContentsChanged(this, index, index);
}
}
Use it as your list model:
将其用作您的列表模型:
m = new MinoListModel<>();
jl = new JList(m);
After updating a user number, update the corresponding entry: m.update(theIndex);
更新用户号后,更新相应的条目: m.update(theIndex);
Alternatively, if you don't want a subclass, you can just replace the JList element after the user number changed: m.setElementAt(theSameElement, theIndex);
. Though this is somewhat cumbersome and having a subclass seems the cleaner approach.
另外,如果你不希望一个子类,你可以在用户数变化更换JList的元素:m.setElementAt(theSameElement, theIndex);
。虽然这有点麻烦,而且拥有一个子类似乎是更简洁的方法。