• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to create JButton Array  RSS feed

 
santosh akella
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
i want to create an array of buttons... and i want to add actionlistener for each of them....
is it possible to do it in swings ? if yes pls tell me how

thank u ..
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two ways:

1) Use an anonymous ActionListener for each JButton you create:



Here the JButtons must be final for them to be accessible to the inner class. Also, I notice that Sun are now recommending against using anonymous inner classes for this kind of thing.

OR


2) Make your class that creates the buttons implement ActionListener. Then do something like this:



Then in your actionPerformed method you must determine which button was clicked on:



This second way is rather messy though, and you need some way to store the names for each button as well. The JButton array also needs class scope.

To be honest it might be better to just create the buttons individually unless you have a *lot* of them...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!