这是我在这里的第一篇文章,我对Java非常感兴趣。这是我为了提高我的Java知识而尝试做的事情。
我有一个按钮,点击时会产生一个洗牌的纸牌组作为Jlist。当再次按下时,我非常希望它刷新 JList,或以某种方式重新创建它。相反,它只是创建一个新列表,所以我现在有 2 个 JLists。
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
}
});
这里的关键是 Swing 使用类似于模型-视图-控制器(但有区别)的模型-视图类型的结构,其中模型保存视图(组件)显示的数据。
您正在做的是创建一个全新的 JList,但您要做的是更新现有和显示的 JList 的模型,或者为同一个现有 JList 创建一个新模型。JList 使用列表模型作为其模式,通常实现为 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
}
});