【问题标题】:Refresh JPanel to display added components in JList刷新 JPanel 以显示 JList 中添加的组件
【发布时间】:2020-03-14 15:32:44
【问题描述】:

所以在我的代码中,我有一个带有菜单栏的框架,可以让我添加面板。 一个面板有一些文本字段,我通过这些文本字段构建对象,将它们添加到 ArrayList,然后将它们显示在 JList 中。

我的问题是,当我按下构建对象的按钮时,面板没有刷新以立即显示 JList 的内容,我实际上必须从 MenuBar 中调用面板才能使其工作。

所以这是我构建 JList 的部分,如果 ArrayList 存在则填充它(这部分在 Panel 的构造函数中):

        listModel = new DefaultListModel();
        if (!MainInterface.listCat.isEmpty()) {
            for (CategorieArticle c : MainInterface.listCat) {
                listModel.addElement(c.toString());
            }
        }
        list = new JList(listModel);

这是构建对象并将它们添加到 ArrayList 的按钮方法(这部分在 ActionListener 方法中):

    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();
        if (o == bEnr) {
            if (tfNoCat.getText().isBlank() || tfNomCat.getText().isBlank()) {
            } else {
                MainInterface.listCat.add(new CategorieArticle(tfNomCat.getText()));
                tfNoCat.setText("");
                tfNomCat.setText("");
                mainPanel.revalidate();
                mainPanel.repaint();
            }
        }
    }

问题是 .revalidate().repaint() 没有刷新面板,以便它通过第一段代码并填充 JList .

非常感谢任何帮助。

【问题讨论】:

标签: java swing arraylist jlist


【解决方案1】:
list = new JList(listModel);

上面的代码什么都不做。您创建了一个新的 JList,但从未将它添加到框架中。

不要一直创建 JList。当您最初为 GUI 创建组件时,只创建一次 JList 并将其添加到添加到框架的滚动窗格中。

要更改 JList 中显示的数据,您只需更新现有 JList 的 ListModel。 JList 会自动重绘自己。

mainPanel.revalidate();
mainPanel.repaint();

也不需要,因为您从未在 ActionListener 的面板中添加任何组件。

,将它们添加到 ArrayList 中,然后将它们显示在 JList 中。

这才是真正的问题。不需要 ArrayList。数据已存储在 ListModel 中。不需要在两个地方都有数据。

只需将数据直接添加到 ActionListener 中的 ListModel。

//MainInterface.listCat.add(new CategorieArticle(tfNomCat.getText()));
CategorieArtical c = new CategorieArticle( tfNomCat.getText() );
listModel.addElement( c.toString() );
//MainInterface.listCat.add( c ); // if you really need the ArrayList for some other reason

您应该在您的类中创建“listModel”作为实例变量,以便可以在 ActionListener 中访问它。

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多