简体   繁体   English

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

[英]actionListener doesn't work after JButton is recreated

I'm coding an UNO card game, I created an array with JButtons that will change in size, the JButtons represent the players hand and all the different cards in it. 我正在编写一个UNO卡片游戏,我创建了一个JButtons阵列,它将改变大小,JButtons代表玩家手牌以及其中所有不同的牌。 When the buttons is created for the first time everything is working, but when I add one card and expand the array, the buttons actionListener is broken. 当第一次创建按钮时,一切正常,但是当我添加一张卡并展开数组时,按钮actionListener就会被破坏。 I think that when the buttons is created for the second time the actionListners is created locally and not globally. 我认为当第二次创建按钮时,actionListners是在本地创建的而不是全局创建的。 I have no idea how to fix the problem, so please help! 我不知道如何解决问题,所以请帮忙! xd 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);
        }
    }

There are a few issues with your code. 您的代码存在一些问题。

It kind of surprise me that even the first time this code may work, because JButton[] playerHandButtons = new JButton[playerHand.size()]; 令我感到惊讶的是,即使这个代码第一次可以工作,因为JButton[] playerHandButtons = new JButton[playerHand.size()]; in the createArray() method create a local variable that should be eligible for garbage collection as soon as you leave the method. createArray()方法中,一旦离开方法,就创建一个应该有资格进行垃圾收集的局部变量。

If you want to keep reference of the buttons you create, you should just use playerHandButtons = new JButton[playerHand.size()]; 如果你想继续引用你创建的按钮 ,你应该只使用playerHandButtons = new JButton[playerHand.size()]; which will assign a new array to the field playerHandButtons. 这将为字段playerHandButtons分配一个新数组。

Same goes to for the createHand() method. createHand()方法也是如此。

There could be other solutions too, but much depend on the listener class. 也可能有其他解决方案,但很大程度上取决于监听器类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM