简体   繁体   中英

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. 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. I think that when the buttons is created for the second time the actionListners is created locally and not globally. I have no idea how to fix the problem, so please help! 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()]; in the createArray() method create a local variable that should be eligible for garbage collection as soon as you leave the method.

If you want to keep reference of the buttons you create, you should just use playerHandButtons = new JButton[playerHand.size()]; which will assign a new array to the field playerHandButtons.

Same goes to for the createHand() method.

There could be other solutions too, but much depend on the listener class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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