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
JListconstructor takes aListModel(an interface), not aDefaultListModel(an implementation). This is an OO principle (Contract) specifying thatJListcan use ANY object that happens to implement theListModelinterface. From the Java tutorial on Object Oriented Programming Concepts:Since
ListModelhas only four methods, it should be very easy for your class to implement them and delegate the operations to your internalDeque. Your class should be declared asand 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 ofListModeland whatever behavior is specified as part of theListModelcontract, in the JavaDoc.Once you have done this, you can construct a
JListpassing an instance of your classModelto the constructor.