• Post Reply Bookmark Topic Watch Topic
  • New Topic

Usage of multiple JButtons  RSS feed

 
Jim Hamrick
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
weeeeeeeeee first post

Ahem.

Im trying to make a jframe with multiple jbuttons, but i dont know how to make the methods to handle all the different button events. I have one button set as runb.addActionListener(this);, but that only works once for public void actionPerformed(ActionEvent ae){}. How do i link different methods to all my different jbuttons?
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Test the value of ae in ONE method...you don't need multiple handlers, just one handler that can tell what the action event originator was...
 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
What you have to do is to add, addActionListener(this) to all the JButtons and the in the actionPerformed(ActionEvent ae) do like this;

String str = ae.getSource();
if (str.equlas(the bttn name)) {

}else if (str.equals(the bttn name)) {

}else {

}
Hope it is clear enough for you to understand, CHEERS
 
Sean Magee
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! It is better design to use inner classes imo. For example if you have a button like this



I would recommend to add the action listener like this



So, in this case, you can make an inner clasw within the class of the GUI, however, I owuld make sure your main GUI does not implemement the listener. So for example you can have something like



In this case, you can call this BtnListener class everytime you want a button to do this specific action, in this case btnButton. If you want another button to do somethign else, just make another inner class, its just better design imo.


-Sean Magee
[ December 07, 2004: Message edited by: Sean Magee ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!