This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Add ActionListener to JButton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Add ActionListener to JButton" Watch "Add ActionListener to JButton" New topic

Add ActionListener to JButton

Thomas Webb

Joined: Feb 12, 2005
Posts: 1
Hi, i have a JPanel with GridLayout(20,20) and i am filling it with buttons like this:

for (int i = 0; i < 400; i++)
gamePanel.add(new JButton("" + i));

I just want to know how i would add an action listener to each button and then identify each button individually when clicked. Thanks.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
luc comeau
Ranch Hand

Joined: Jan 20, 2005
Posts: 97
i never did like that way that was shown above...i hate cramming code like that ...i duno just a preference thing though..
what i always to is ,
1:make your class implement the ActionListener interface
2:you must then have an ActionPerformed method that looks like this
--->public void actionPerformed(ActionEvent e)
a short short example may help

you can do this for as many buttons as you want, and just folow the same basic outline i have shown.Hope it helps some, or atleast gives you another perspective.

National Research Council<br />Internet Logic Department
I agree. Here's the link:
subject: Add ActionListener to JButton
It's not a secret anymore!