Awesome!
You are very close to an answer. I don't think giving you exact code is going to help you learn something, but I have a handy hint for you that's going to push you in the right direction:
The following section of code displays a main panel, filled with some buttons. If you click on one, it identifies itself. The buttons are added to a list at runtime, so, in theory, you can have as many buttons as you want. Using this, you can do the same in your code. Believe it or not, this piece of code creates 150 buttons
Please let me know if you managed to get your code working.
Best regards,
Ewald
package lotsofbuttons;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class LotsOfButtons
extends JFrame
implements ActionListener
{
private static final int BUTTONS = 150;
private List<JButton> buttons = new LinkedList<JButton>();
public LotsOfButtons()
{
setupFrame();
setupButtons();
}
protected void setupFrame()
{
this.setSize(640, 480);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
this.setLayout(new FlowLayout(FlowLayout.LEFT));
}
/**
* Create all of our buttons, add the action listener,
* add them to the list and then add them to the main panel.
*/
protected void setupButtons()
{
for (int i = 0; i < BUTTONS; i++)
{
JButton button = new JButton("" + i);
button.addActionListener(this);
buttons.add(button);
this.add(button);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
LotsOfButtons app = new LotsOfButtons();
app.setVisible(true);
}
/**
* Loop through all our buttons, if it's the one
* that was clicked, display the correct message
* @param e
*/
public void actionPerformed(ActionEvent e)
{
for (JButton jButton : buttons)
{
if (e.getSource().equals(jButton))
{
JOptionPane.showMessageDialog(this, "You pressed " + jButton.getText());
break;
}
}
}
}