【问题标题】:Updating/recreating a JList更新/重新创建 JList
【发布时间】:2016-11-10 04:23:06
【问题描述】:

这是我在这里的第一篇文章,我对 Java 非常熟悉。这是我正在努力提高我的 Java 知识的东西。

我有一个按钮,单击该按钮会生成一个洗牌的牌组作为 Jlist。 当再次按下时,我非常希望它刷新 JList,或者以某种方式重新创建它。相反,它只是 创建一个新列表,所以我现在有 2 个 JList。

        button1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {

            cards.choseCards(); //Creates an ArrayList with the suffled cards
            JList<String> displayList = new JList<>(cards.deck.toArray(new String[0]));
            frame.add(displayList);
            frame.pack();
            cards.cleanUpDeck(); //Removes all the cards from the ArrayList
        }
    });

【问题讨论】:

  • actionPerformed() 方法的第二行创建了一个新的JList,因此每次按下按钮时,都会在框架中添加一个新的JList。尝试在方法和内部类之外创建列表,并在方法内更新数据。

标签: java swing arraylist jbutton jlist


【解决方案1】:

这里的关键是 Swing 使用模型视图类型的结构类似于 模型视图控制器(但有所不同),其中模型保存视图(组件)显示的数据.

您正在做的是创建一个全新的 JList,但您想要做的是更新现有和显示的 JList 的 模型,或者为相同的现有 JList 创建一个新模型列表。 JList 使用 ListModel 作为其模式,通常作为 DefaultListModel 对象实现,因此您需要更新或替换此模型,例如创建一个新的 DefaultListModel 对象,然后通过调用其 setModel(ListModel model) 方法将其插入现有 JList。

例如,您的代码可能看起来像这样(由于我们不知道您的真实代码是什么样子,因此我们进行了 很多 次猜测):

button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // create new model for the JList
        DefaultListModel<String> listModel = new DefaultListModel<>();
        cards.choseCards(); //Creates an ArrayList with the suffled cards

        // add the cards to the model. I have no idea what your deck field looks like
        // so this is a wild guess.
        for (Card card : cards.deck) {
            listModel.addElement(card.toString());  // do you override toString() for Card? Hope so
        }

        // Guessing that your JList is in a field called displayList.
        displayList.setModel(listModel);  // pass the model in
        cards.cleanUpDeck(); //Removes all the cards from the ArrayList
    }
});

【讨论】:

  • 我不得不稍微调整一下,但这正是我所需要的!非常感谢您的帮助:-)
猜你喜欢
  • 1970-01-01
  • 2014-03-09
  • 2011-10-12
  • 2014-01-12
  • 2016-07-15
  • 2012-10-07
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多