我写了一个包含 Deque<T>
的类(我们称之为 Model.java) , 以及对项目进行入队和出队的方法。现在我试图将它与 GUI JList 联系起来。我对如何以某种方式使用我的“模型”数据——Deque——作为 JList 想要的 DefaultListModel 感到困惑。我仍在努力真正理解 OO 概念,因为它们适用于 GUI 编程。 DefaultListModel 文档指出:
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 ....
有没有办法让 DefaultListModel 使用我的 Deque<T>
而不是 Vector,从而允许我的 Model.java 代码在很大程度上保持不变,同时免费提供所有监听/通知行为?或者我是否必须重写 Model.java 以使用 DefaultListModel 而不是 Deque<T>
?
最佳答案
请注意,JList
构造函数采用 ListModel
(接口(interface)),而不是 DefaultListModel
(实现)。这是一个 OO 原则(契约),指定 JList
可以使用恰好实现 ListModel
接口(interface)的任何对象。来自 Object Oriented Programming Concepts 上的 Java 教程:
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.
由于 ListModel
只有四个方法,您的类应该很容易实现它们并将操作委托(delegate)给您的内部 Deque
。您的类(class)应声明为
public class Model implements ListModel
{
....
并将包含四个额外的方法来实现 ListModel
的方法。这些实现可以在幕后完成您需要的任何事情,但必须遵守 ListModel
的定义以及在 JavaDoc 中作为 ListModel
契约的一部分指定的任何行为。
完成此操作后,您可以构造一个 JList
,将您的类 Model
的实例传递给构造函数。
关于java - 如何将 Java Deque<T> 转换为 DefaultListModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6728025/