将JList .setModel()方法与类作为参数一起使用 [英] Using the JList .setModel() method with a class as an argument

查看:122
本文介绍了将JList .setModel()方法与类作为参数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的最终目标是拥有一个JList,该JList可以在运行时刷新其内容,并且我已经找到了一种解决方案,可以从本文中使用

My ultimate goal is to have a JList which refreshes its content at runtime, and I have found a solution that works from this post here on SO, however I am curious why my original idea did not.

截至目前,我具有类似此设置的功能,并且可以正常工作:

As of now, I have something like this setup and it works:

DefaultListModel default = new DefaultListModel();

for(int i = 0; i < array.size() ; ++i){
   test.addElement(array.get(i));
}
list.setModel(default);

下面是我的原计划.我希望有一个实现ListModel的类作为参数传递,希望它可以刷新JList.

Below was my original plan. I wanted to have a class which implemented ListModel be passed as an argument, hoping it would refresh the JList.

SomeClass test = new SomeClass(); //Implements ListModel
list.setModel(test);

SomeClass test = new SomeClass(); //Implements ListModel
list = new JList(test);

这些工作都没有,这使我感到困惑.后两种方法能否以某种方式工作,代码会更简洁.

Neither of these work, which confuses me. Could these last two methods work some how, the code is so much cleaner.

谢谢.

推荐答案

如果正确实现ListModel,第一种方法应该可以工作.关键是,当您更改数据时,您需要调用:

The first approach should work if you implement the ListModel correctly. The key is that when you change the data you need to invoke:

fireContentsChanged(...);

从AbstractListModel(我假设您要扩展).调用此方法将告诉JList重新绘制自身.

from the AbstractListModel (which I assume you extend). Invoking this method will tell the JList to repaint itself.

第二种方法行不通,因为您只是创建了一个位于内存中的新JList组件.创建该组件不会将其添加到GUI.因此,如果使用这种方法,则需要从GUI中删除原始的JList,然后将新的JList添加到GUI.这不是很方便,并且是不应该使用此方法的一个很好的理由.设置模型始终是首选方法.

The second approach won't work because you just create a new JList component that is sitting in memory. Creating the component does not add it to the GUI. So if you use this approach you need to remove the original JList from the GUI and then add your new JList to the GUI. This is not very convenient and is a good reason why this approach should not be used. Setting the model is always the preferred approach.

这篇关于将JList .setModel()方法与类作为参数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆