Dynamic creation of Buttons, mouseClick

Hi,

I'm creating the buttons in dynamic way.

for (int i = 0; i <parameters.length; i++ ){

InputDataSource_Array=parameters[i].get_InputDataSource().split("\\.");

caption=InputDataSource_Array[(InputDataSource_Array.length-1)]+":"+parameters[i].get_Algorithm().UID();

ToggleButtons[i] =new javax.swing.JToggleButton();

ToggleButtons[i].setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/parameter-red.gif")));

ToggleButtons[i].setText(caption);

ToggleButtons[i].setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

ToggleButtons[i].addMouseListener(new java.awt.event.MouseAdapter(){

publicvoid mouseClicked(java.awt.event.MouseEvent evt){

togglePanel(i);

}

});

gridBagConstraints =new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = (i+1)*2-1;

//System.out.println(gridBagConstraints.gridy);

gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;

gridBagConstraints.weightx = 100.0;

add(ToggleButtons[i], gridBagConstraints);

}

and I want to invoke togglePanel(i) on mouseClick.

But compilator says that "local variable i is accessed from within inner class".

How can I do it properly?

Thank you!>

[1863 byte] By [mustheroa] at [2007-11-27 8:27:55]
# 1

final int icopy = i;

ToggleButtons[i].addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent evt) {

togglePanel(icopy );

}

});

Hippolytea at 2007-7-12 20:17:44 > top of Java-index,Java Essentials,Java Programming...
# 2
An alternative approach would be to associate an index with a button using putClientProperty/getClientProperty. Then a single listener would suffice.
Hippolytea at 2007-7-12 20:17:44 > top of Java-index,Java Essentials,Java Programming...
# 3

Swing related questions should be posted in the Swing forum.

You should be using a generic listener as mentioned above, but I would just use the ActionCommand to differentiate each button. Maybe this simple example, from the Swing forum. will get your started:

http://forum.java.sun.com/thread.jspa?forumID=57&threadID=609795

camickra at 2007-7-12 20:17:44 > top of Java-index,Java Essentials,Java Programming...