简体   繁体   中英

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

I am creating a java application using NetBeans 7.3.
I have a "Create New Foo" wizard that shares a JPanel across multiple frames.
The JPanel object implements a JList that I have setup as shown here:

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:

//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.

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.

A JList needs an instance of ListModel to work. This instance could be an instance of DefaultListModel , but you could create your own ListModel implementation and use it instead of DefaultListModel .

BTW, note by the constructors of JList construct a JList with a ListModel that is not an instance of 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 .

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