【发布时间】: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