Tricky problem. Change button name with each for-loop

Hi all,

I would like to implement a 'for loop' to add buttons to my panel depending on the value of max_number.

The postion of these buttons will also change with each passing of the loop.

The code below implements this. But when I click the buttons they only return the action listener of the last button drawn. This is because the JButton my_button is reused in each pass through the loop.

What I need is to change the name of the button on each passing of the loop so that I create a new button each time with it's own unique action listener.

Is there a way of adding/appending the value of 'i' to the button name each time the for loop is run?

For example

When i = 0 -> JButton my_button0 = ...

When i = 1 -> JButton my_button1 = ...

etc, etc,

[CODE]

for (i = 0; i < max_number; i++)

{

JButton my_button = new JButton(Integer.toString(i));

my_button.addActionListener( new ActionListener()

{ public void actionPerformed(ActionEvent event)

{ do something depending on the value of 'i' }});

addComponent(my_button, (2*i+1) , 4 , 1 , 1);//add newly created button to position x = (2*i+1), y = 4

} //end for

[/CODE]

[1258 byte] By [johnnyhall81a] at [2007-9-30 2:17:06]
# 1

You can set the name of the button by using

my_button.setName("whatevername");

Generate whatevername - for example "Button1".

Then use a generic ActionListener and perform an action related to the button pressed.

Right now the code is setting up a different listener for each button.

rykk

rykk.a at 2007-7-16 13:25:43 > top of Java-index,Archived Forums,Swing...
# 2
Got it sorted in http://forum.java.sun.com/thread.jsp?forum=31&thread=499445. Thanks anyway.
johnnyhall81a at 2007-7-16 13:25:43 > top of Java-index,Archived Forums,Swing...