【问题标题】:actionListener doesn't work after JButton is recreated重新创建 JButton 后 actionListener 不起作用
【发布时间】:2019-05-13 10:48:33
【问题描述】:

我正在编写一个 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);
        }
    }

【问题讨论】:

  • 这很奇怪:player.add(playerHandGUI[i]) -- 你为什么将playerHandGUI[i] 添加到播放器而不是你刚刚创建的按钮?您在哪里将该按钮添加到 GUI?我认为我们正在处理一个可能的印刷错误。
  • playerHandButtons 被称为 playerHandGUI 我更改了问题中的名称以澄清。我在问题中对其进行了编辑,但仍然是同样的问题。感谢您的通知!
  • 你能贴出动作监听的代码和添加和移除卡片的代码吗?
  • 上下文不足以找到问题。请提供更多详细信息。

标签: java arrays swing jbutton actionlistener


【解决方案1】:

您的代码存在一些问题。

让我感到惊讶的是,即使是第一次这段代码也可以工作,因为 JButton[] playerHandButtons = new JButton[playerHand.size()];createArray() 方法中创建了一个局部变量,一旦您离开该方法,该变量就应该有资格进行垃圾收集。

如果你想保留你创建的按钮的引用,你应该只使用playerHandButtons = new JButton[playerHand.size()];,它将为字段playerHandButtons分配一个新数组。

createHand() 方法也是如此。

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

【讨论】:

  • 感谢所有帮助,我找到了另一个解决方案。我创建了一个包含最大值的数组,而不是创建一个会改变大小的数组,它只会显示与 playerHand 中卡片相同数量的按钮,并且 actionListeners 将保持不变。
猜你喜欢
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 2013-06-05
  • 2013-04-26
相关资源
最近更新 更多