[英]actionListener doesn't work after JButton is recreated
我正在編寫一個UNO卡片游戲,我創建了一個JButtons陣列,它將改變大小,JButtons代表玩家手牌以及其中所有不同的牌。 當第一次創建按鈕時,一切正常,但是當我添加一張卡並展開數組時,按鈕actionListener就會被破壞。 我認為當第二次創建按鈕時,actionListners是在本地創建的而不是全局創建的。 我不知道如何解決問題,所以請幫忙! XD
// playerHandButtons = the array with the buttons that is recreated
// playerHand = a stack that contains the players cards in the hand
// when the array is created for the first time
JButton [] playerHandButtons = new JButton[7];
// you start with 7 cards
public void createArray() {
JButton[] playerHandButtons = new JButton[playerHand.size()];
for (int i = 0; i < playerHandButtons .length; i++) {
playerHandButtons [i] = new JButton("" + playerHand.elementAt(i));
player.add(playerHandButtons [i]);
playerHandButtons [i].addActionListener(this);
}
}
// player = is the panel that displays all the cards
public void createHand() {
player.removeAll();
player.repaint();
player.revalidate();
JButton[] playerHandButtons = new JButton[playerHand.size()];
for (int i = 0; i < playerHandButtons .length; i++) {
playerHandButtons [i] = new JButton("" + playerHand.elementAt(i));
player.add(playerHandButtons [i]);
playerHandButtons [i].addActionListener(this);
}
}
您的代碼存在一些問題。
令我感到驚訝的是,即使這個代碼第一次可以工作,因為JButton[] playerHandButtons = new JButton[playerHand.size()];
在createArray()
方法中,一旦離開方法,就創建一個應該有資格進行垃圾收集的局部變量。
如果你想繼續引用你創建的按鈕 ,你應該只使用playerHandButtons = new JButton[playerHand.size()];
這將為字段playerHandButtons分配一個新數組。
createHand()
方法也是如此。
也可能有其他解決方案,但很大程度上取決於監聽器類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.