gpt4 book ai didi

java - 重新创建 JButton 后,actionListener 不起作用

转载 作者:行者123 更新时间:2023-12-02 05:44:24 24 4
gpt4 key购买 nike

我正在编写一个 UNO 纸牌游戏,我创建了一个带有 JButton 的数组,该数组的大小会发生变化,JButton 代表玩家的手牌以及其中的所有不同纸牌。当第一次创建按钮时,一切正常,但是当我添加一张卡并展开数组时,按钮 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() 也是如此方法。

也可能有其他解决方案,但很大程度上取决于listener类。

关于java - 重新创建 JButton 后,actionListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56110811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com