[英]Updating/recreating a JList
這是我在這里的第一篇文章,並且我對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
}
});
此處的關鍵是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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.