简体   繁体   English

Java / Netbeans:JList.getModel()返回一个ListModel而不是DefaultListModel

[英]Java/Netbeans: JList.getModel() returns a ListModel instead of a DefaultListModel

I am creating a java application using NetBeans 7.3. 我正在使用NetBeans 7.3创建Java应用程序。
I have a "Create New Foo" wizard that shares a JPanel across multiple frames. 我有一个“创建新Foo”向导,该向导跨多个框架共享一个JPanel。
The JPanel object implements a JList that I have setup as shown here: JPanel对象实现了我已设置的JList,如下所示:

http://img811.imageshack.us/img811/5717/customcodepvmarketlist.jpg http://img811.imageshack.us/img811/5717/customcodepvmarketlist.jpg

Using another function, I want to be able to test the contents of the JList, like so: 使用另一个功能,我希望能够测试JList的内容,如下所示:

//Adds a market to the list, if it doesn't exist.
//Removes a market from the list, if it does exist.
//If removing a market causes the list to become empty,
//insert 'None'

public String modifyMarket(String market) {
    if(pvMarketList.getModel().contains(market)) {
        //More Code   
    }         
}

I can't do the above test on '.contains(market)' because .getModel() is returning a ListModel instead of a DefaultListModel. 我无法在“ .contains(market)”上进行上述测试,因为.getModel()返回的是ListModel而不是DefaultListModel。

What is the problem? 问题是什么? How can I fix this? 我怎样才能解决这个问题?

UPDATE 更新
I might be able to work around the issue by casting the ListModel as a DefaultListModel, but I remain confused as to why ListModel is what is being returned. 我可以通过将ListModel强制转换为DefaultListModel来解决此问题,但是对于为什么要返回ListModel仍然感到困惑。

A JList needs an instance of ListModel to work. JList需要ListModel的实例才能工作。 This instance could be an instance of DefaultListModel , but you could create your own ListModel implementation and use it instead of DefaultListModel . 该实例可以是DefaultListModel的实例,但是您可以创建自己的ListModel实现并使用它代替DefaultListModel

BTW, note by the constructors of JList construct a JList with a ListModel that is not an instance of DefaultListModel. 顺便说一句,由JList的构造方法注意的是,使用ListModel构造JList,该ListModel不是DefaultListModel的实例。

If you know that it is a DefaultListModel , because that's what you passed when constructing the list, then you can safely cast the returned ListModel to DefaultListModel . 如果您知道它是DefaultListModel ,因为这是构造列表时传递的内容,则可以安全地将返回的ListModelDefaultListModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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