How can I iterate through an array of JButtons to check if a button has been pressed in a Java GUI?

33 Views Asked by At

I'm trying to make a card game in Java GUI, and I can't figure out how to iterate through the player's hand to check if a card in the hand has been pressed. When I press one of the buttons in handButtons, all it does is print "a" about a dozen times, but never enters the if statement. (Update: I fixed it. I just moved my code to be outside of the (e.getSource() == startButton) heading)

@Override
public void actionPerformed(ActionEvent e) 
{   
    int pIndex; 
    if (e.getSource() == startButton)
    {
        pIndex = whoGoesFirst();
        Trick t = new Trick(players[pIndex], cardsInTrick);
        for (int p = 0; p < NUM_OF_PLAYERS; p++) // Goes through all players' turns
        {
            for (int i = 0; i < handButtons.length; i++) // Goes through all cards in the hand 
            // (handButtons is an array of JButtons)
            {
                System.out.println("a"); 
                // When I run this, it prints "a" a lot of times, but never "b" or "c"
                if (e.getSource() == handButtons[i]) 
                {
                    System.out.println("b");
                    if (t.isLegal(players[pIndex], players[pIndex].getHand().get(i)))
                    {
                        System.out.println("c");
                        trickCardSlots[pIndex].setIcon((ImageIcon) handButtons[pIndex].getIcon());
                    }
                }
            }
        }
    }    
}
0

There are 0 best solutions below