How to turn Java Deque <T> into DefaultListModel?

I wrote a class (let's call it Model.java) that contains Deque<T> , with methods for placing and deleting objects. Now I am trying to associate this with the JList GUI. I am puzzled how to somehow use my "model" data - Deque - like the DefaultListModel that JList wants. I am still struggling to get OO ideas as they apply to GUI programming. The default documentation of ListModel states:

This class freely implements the java.util.Vector API, since it implements java.util.Vector version 1.1.x, does not have a collection class support, and notifies ListDataListeners of any changes. He is currently delegating a vector ....

Is there a way to get DefaultListModel to use my Deque<T> instead of Vector, so that my Model.java code stays pretty much the same, providing all listening / notification of violation for free? Or do I need to rewrite Model.java to use DefaultListModel instead of Deque<T> ?

+3
source share
3 answers

Note that the JList constructor accepts a ListModel (interface), not a DefaultListModel (implementation). This is the principle of OO (contract), indicating that the JList can use ANY object that implements the ListModel interface. From the Java tutorial in the Object Oriented Programming Concept :

An interface is a contract between a class and the outside world. when a class implements an interface, it promises 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 operations to your internal Deque . Your class must be declared as

 public class Model implements ListModel { .... 

and will contain four additional methods that implement ListModel methods. Implementations can do everything you need in shells, but must adhere to the definition of ListModel and any behavior specified as part of the ListModel contract in JavaDoc.

Once you do this, you can build a JList by passing an instance of your Model class to the constructor.

+5
source

For JList you do not need to use DefaultListModel , but only some implementation of the ListModel interface. And the latter is very achievable with Deque .

+1
source

I did not know what to do for addListDataListener()

AbstractListModel may be a good starting point, as it already implements the prescribed EventListenerList for working with listeners and events.

+1
source

All Articles