简体   繁体   中英

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

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

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM