How do I turn a Java Deque<T> into a DefaultListModel?

微笑、不失礼 提交于 2019-12-12 16:27:28

问题


I wrote a class (let's call it Model.java) that contains a Deque<T>, with methods for enqueuing and dequeuing items. Now I'm trying to tie this to a GUI JList. I'm baffled by how to somehow use my "model" data -- the Deque -- as a DefaultListModel that JList wants. I'm still struggling to really get OO concepts, as they apply to GUI programming. DefaultListModel documentation states:

This class loosely implements the java.util.Vector API, in that it implements the 1.1.x version of java.util.Vector, has no collection class support, and notifies the ListDataListeners when changes occur. Presently it delegates to a Vector ....

Is there some way to get the DefaultListModel to use my Deque<T> instead of a Vector, thus allowing my Model.java code to remain largely unchanged while providing all the listening/notifying behavior for free? Or do I have to rewrite Model.java to use a DefaultListModel instead of Deque<T>?


回答1:


Notice that the JList constructor takes a ListModel (an interface), not a DefaultListModel (an implementation). This is an OO principle (Contract) specifying that JList can use ANY object that happens to implement the ListModel interface. From the Java tutorial on Object Oriented Programming Concepts:

An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface.

Since ListModel has only four methods, it should be very easy for your class to implement them and delegate the operations to your internal Deque. Your class should be declared as

public class Model implements ListModel
{
     ....

and will contain four additional methods that implement the methods of ListModel. The implementations can do whatever you need under the covers, but must adhere to the definition of ListModel and whatever behavior is specified as part of the ListModel contract, in the JavaDoc.

Once you have done this, you can construct a JList passing an instance of your class Model to the constructor.




回答2:


For JList, you don't have to use DefaultListModel, just some implementation of the ListModel interface. And the latter is very achievable using a Deque.




回答3:


I didn't know what to do for addListDataListener()

AbstractListModel might be a good starting point, as it already implements the prescribed EventListenerList methods to deal with listeners and events.



来源:https://stackoverflow.com/questions/6728025/how-do-i-turn-a-java-dequet-into-a-defaultlistmodel

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