简体   繁体   English

JList 不会在 javax.swing 中更新

[英]JList won't update in javax.swing

I have a simple code with a JFrame, a JButton, and JList which content is supposed to update once the button is clicked:我有一个简单的代码,其中包含 JFrame、JButton 和 JList,一旦单击按钮,内容应该更新:

private void btnUpdateListActionPerformed(java.awt.event.ActionEvent evt) {    
                                 
    //A default list model containing two strings is created.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("hello");
    listModel.addElement("bye");

    //The JList is updated so that it contains the strings of the default list model.
    list = new JList(listModel);
}  

However, after pressing the button nothing happens;但是,按下按钮后没有任何反应; the list remains with its original values:该列表保持其原始值:

在此处输入图像描述


How do I resolve this so that the list updates as desired?如何解决此问题,以便列表根据需要更新?

Don't create a new JList不要创建新的 JList

//The JList is updated ....
list = new JList(listModel);

This does not "update the JList", but instead creates a new instance, one that is never displayed, and the displayed JList, which now is no longer referred to by the list variable, isn't changed at all.不会“更新 JList”,而是创建一个从未显示的新实例,并且显示的 JList(现在不再由 list 变量引用)根本没有更改。

Instead, set the model of the existing list:相反,设置现有列表的 model :

list.setModel(listModel);

The main issue is that you're confusing variable with instance: you need to update the state of the existing instance, not update the variable with an entirely new instance.主要问题是您将变量与实例混淆:您需要更新现有实例的state而不是使用全新实例更新变量。

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

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