Hello everyone

As you can see, this is my first post.
We're trying to write a cards game and it uses 12 cards.
Someone taught me to put the buttons in an array, which i think is a really good idea.

I'm encountering one problem, how do i create an action listener for these buttons?

This is my code for now:
(By the way, the cards are divided in 3 rows and 4 columns)

int counter = 0; //number of the card
for(int row =1; row <=3;row++)
{
	for(int col=1;col <=4;col++)
	{
	btnCard[counter] = new JButton();
	btnCard[counter].setIcon(new ImageIcon( getClass().getResource( "empty.jpg" )));
	addComponent(btnCard[counter],row,col,1,1,0,0);
				
	btnCard[counter].addActionListener
	(
		new ActionListener()
		{  
		
		public void actionPerformed( ActionEvent event )
	           {
			for(int counter = 0; counter < 12; counter++)
			{
			if(/*This is not right*/btnCard[counter].getActionCommand() == event.getActionCommand())
									{
										//selectedCards.addCard(gameCards[counter]);
										JOptionPane.showMessageDialog(null, "You pushed button " + counter);
									}
			}
		} 
	        }
	);
	counter ++;
	}
}

This code gives te following result: 12 messagedialogs are shown telling "You pushed button 0", "You pushed button 1", ..., "You pushed button 11".

Thanks in advance.
Greets, Kenny.

Since you do not use setActionCommand("String"), the actionCommand will be based on the text shown on the button. Since they all have the same text (i.e. none) all of the Dialogs will be shown, since all of the ActionListeners (and you have a separate one for each button) loop through all the buttons.

That loop (inside the ActionListener) is completely unnecessary, as each button will have it's own ActionListener. Just simply have it perform whatever action you want it to perform, as the button to which it is added is the only thing that ActionListener reacts to.

Oh, thats nice to know :-O
Thank you :)

Greets, Kenny.

I'm encountering the folowing problem, i can't access my counter.

That way, i can't access my cards :(.

Any hints?
Thanks in advance.

Greets.

Yes, use setActionCommand to set the actionCommand to the counter's value, then use getActionCommand in the Listener to display it. That is hijacking the purpose of the actionCommand, a bit, but heh, nobody's perfect.

Thank you for your help masijade.

Sorry if it looks like i'm trying to let others make my project ;).
It's not what i meant to do :).

Greets, Kenny.

Don't worry. I jump all over most of the people that simply dump their assignments here and expect to have it finished for them.

That's not what you did. This is how a forum is suppossed to work, I gave you a few ideas/pointers about what to do, but left you to do it, and you did it.

You'd be suprised at how many people scoff at that and try to get us to simply post working code for them that they can then cut-n-paste and turn in as their assigment.

They don't get it, and when they do, it's not what they expect. ;-)

K :).

By the way, it works.
Not the whole game ofcourse, but at least my action handler works :)

my first post! sorry to post in an old thread, but i have a question related to this.

my situation is this: i want to make a paint-like program for a project in class, with "quick select colors," an array of colors, and an array of buttons (with only background color), but i don't want to have to make an action listener for each button.

i know the VB equivalent is something like BUTTON1_ONCLICK(integer index,...) setcolor(colorarray(index)) but i am unsure of the way i would do this in java a link to the sun tutorial that explains, or api would be sufficient, or any suggestions

thanks

my previous work is on my site matrixpeckham.googlepages.com

my first post! sorry to post in an old thread, but i have a question related to this.
my situation is this: i want to make a paint-like program for a project in class, with "quick select colors," an array of colors, and an array of buttons (with only background color), but i don't want to have to make an action listener for each button.
i know the VB equivalent is something like BUTTON1_ONCLICK(integer index,...) setcolor(colorarray(index)) but i am unsure of the way i would do this in java a link to the sun tutorial that explains, or api would be sufficient, or any suggestions
thanks
my previous work is on my site

It might be useful to, upon creation of your buttons, also set their action commands to their number value in the array.

I.E...--

JButton[] buttons = {new JButton("First"), new JButton(Second) /*However many you need here...*/};


for(int i = 0; i < buttons.length; i++)
{
button.setActionCommand("" + i);
}

--and simply use their actionCommand in respect with their array indice number with just one actionListener--

public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equalsIgnoreCase("0"))
{
//code for button[0]
}
else if(e.getActionCommand().equalsIgnoreCase("1"))
{
//code for button[1]
}
//etc...
}

Edited 3 Years Ago by happygeek: fixed formatting

The code that Alex Edwards posted will work for that scenario, but the action listener code can become quite long, verbose, and repetitive for your button array. A cleaner way to handle that would be to create a small action class for those buttons, like

class ColorButtonAction extends AbstractAction{
    Color buttonColor;
    
    public ColorButtonAction(Color buttonColor){
        this.buttonColor = buttonColor;
    }
    public void actionPerformed(ActionEvent e) {
        // your code to set the color here
        setColor(buttonColor);
    }
}

and when you create the buttons for the array just create the appropriate action instance

new JButton(new ColorButtonAction(Color.BLUE) )
// or you can set the action on an existing button 
button[0].setAction(new ColorButtonAction(Color.BLUE));

The alternative to doing that is to simply create an enumeration that implements the ActionListener interface. I created a test class to show you the syntax--

import java.awt.event.*;

public class TestEnum
{
	static class InnerClass
	{
		public enum ButtonListener implements ActionListener
		{
			FIRST
			{
				public void actionPerformed(ActionEvent e)
				{
                                       //code for first button...
				}
				public String toString()
				{
					return "First Button";
				}
			},//end first ActionListener
			SECOND
			{
				public void actionPerformed(ActionEvent e)
				{
                                    //code for second button...
				}
				public String toString()
				{
					return "Second Button";
				}
			},//end second ActionListener
			THIRD
			{
				public void actionPerformed(ActionEvent e)
				{
                                    //code for third button...
				}
				public String toString()
				{
					return "Third Button";
				}
			};//end third ActionListener
		};//end enumerated type
	}//end static class InnerClass
}//end class TestEnum

Then iterate through your array of buttons and add each individual ActionListener from the class

//From the same class in a different section of TestEnum...

private JButton[] buttons;
private final int B_AMOUNT = 9;

public void initializeButtons()
{
          buttons = new JButton[B_AMOUNT];
 
          for(int i = 0; i < B_AMOUNT; i++)
          {
                buttons[i].addActionListener(InnerClass.ButtonListener.values()[i]);
          }
}

That's a unique way of structuring it, but if all of the listeners are performing essentially the same action with differing parameters then that is still too much redundant code. There is no reason to repeat that much boilerplate code unless each operation is distinct to a degree that cannot easily be represented as a shared class.

In the case of the poster's color buttons, a simple action class is all that is needed to encapsulate the action for each case and minimize the repetitive code.

well i basically decided to use that the previously mentioned code, set action command seems perfect, just the number and parse it to get the color, basically a one line function. thanks anyway though i'm sure that will come in handy for other projects.

This question has already been answered. Start a new discussion instead.