Using the JList .setModel() method with a class as an argument

蓝咒 提交于 2019-12-23 10:01:12

问题


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);

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);

or

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.

Thanks.


回答1:


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(...);

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

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.




回答2:


The first case seems like a solution in my mind. Can you provide a testable example?

The second case will not work because you are just reusing a variable and are not actually changing the JList on the Gui. I am assuming you already added this list to the guy earlier in code.




回答3:


Most likely your implementation of ListModel is wrong.




回答4:


Why not using:

DefaultListModel<String> lstList = new DefaultListModel<String>();


来源:https://stackoverflow.com/questions/4231820/using-the-jlist-setmodel-method-with-a-class-as-an-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!