简体   繁体   English

为什么我的DefaultListModel没有显示在我的JList上?

[英]Why is my DefaultListModel not showing up on my JList?

I have the following method. 我有以下方法。

           DefaultListModel getModelForCabin(Cabin cabin) {

 List<Camper> listAdded= new ArrayList<Camper>(getOrCreateGroup(cabin));

 DefaultListModel<Camper> dfm= new DefaultListModel<Camper>();
    for(Camper c: listAdded){
        if(!dfm.contains(c)){
            dfm.addElement(c);
        }

    }
    //System.out.println(listAdded);
    //System.out.println(dfm);

    return dfm;
}

Then, I set this method inside the JList like this... 然后,我像这样在JList中设置此方法...

 JList list = new JList(getModelForCabin((Cabin)comboBox.getSelectedItem()));
scrollPane_1.setViewportView(list);

In the method, if I print the dfm and listAdded as shown in the system print line, it shows the both. 在该方法中,如果我按系统打印行中所示打印dfm和listAdded,则会显示两者。

If I type this... 如果我输入这个...

System.out.println(getModelForCabin((Cabin)comboBox.getSelectedItem());   

It prints out the model as well. 它也打印出模型。

What it will not do though, is add the model to the JList. 它不会做的是将模型添加到JList中。 I've tried changing around the code, deleting the JList and making a new one, and rearranging the code. 我尝试过更改代码,删除JList并制作一个新的代码,然后重新排列代码。

No matter what I do, it will not work. 不管我做什么,都行不通。

So my list prints fine, my DefaultListModel prints fine, my HashMap that prints the Cabin and Campers works fine, but the JList will not print the model. 因此,我的列表打印正常,我的DefaultListModel打印良好,我的打印Cabin和Campers的HashMap工作正常,但是JList将不会打印模型。

Added: 添加:

     JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setBounds(361, 205, 296, 339);
    getContentPane().add(scrollPane_1);

     list = new JList(getModelForCabin((Cabin)comboBox.getSelectedItem()));
    scrollPane_1.setViewportView(list);

I figured out the problem was because I wasn't setting the model. 我发现问题是因为我没有设置模型。 If the model is a local DefaultListModel, it has to be set in the main class using the setModel method. 如果模型是本地DefaultListModel,则必须使用setModel方法在主类中对其进行设置。

I needed to reference the JList, then do the setModel like this.... 我需要引用JList,然后像这样执行setModel。

            list.setModel(getModelForCabin((Cabin)comboBox.getSelectedItem()));

Where list is the variable of the JList, and getModelForCabin(Cabin cabin) is the method which returns the DefaultListModel. 其中list是JList的变量,而getModelForCabin(Cabin cab)是返回DefaultListModel的方法。

It was added to both the action listener for the add button, as well as a refresh button that was created when opening the class. 它已添加到“添加”按钮的动作侦听器以及打开类时创建的刷新按钮。

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

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