0

I'm new in Java swing, and I have a problem. I made for-loop for creating buttons and now I want automatically give them names or some kind of marks for future recognition (I will need name of clicked button to make it a variable).

How can I give them names in my loop? Thank you.

Here is code of my for-loop:

     for (int aa=1; aa<65; aa++) 
                {
                    JButton button = new SquareButton("");
                    gui.add(button); 
                    button.addActionListener((ActionListener) button);

                }    
2
  • 1
    Store them in a Collection, or put button.setName("button"+aa) alternative, you can use Action and setName and actionListener all there.. and then call button.setAction(myAction); Commented Dec 22, 2013 at 19:39
  • @nachokk Thank you for answer and effort! Commented Dec 22, 2013 at 21:46

1 Answer 1

6

I will need name of clicked button to make it a variable).

You don't need a variable to work with the clicked button. Instead you get a reference to the button that was clicked from the ActionListener code:

public void actionPerformed(ActionEvent e)
{
    JButton button = (JButton)e.getSource();
    // do processing on the clicked button.
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for answer and effort!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.