• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Add ActionListener to JButton

 
Thomas Webb
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
luc comeau
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic