Meaningless Drivel is fun!
The moose likes Swing / AWT / SWT and the fly likes Adding ActionListeners to JButtons Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Adding ActionListeners to JButtons" Watch "Adding ActionListeners to JButtons" New topic

Adding ActionListeners to JButtons

Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
Hi there...... I have a quick question..... I have an application that reads through a ResultSet... while I'm reading that ResultSet, I am creating new JButtons..... Now I need to add an ActionListener to those JButtons...... but they are not visible to the actionPerformed method. Sooooo I thought I'd try to add an ActionListener as I created the buttons with the following code:

However this seems a bit excessive to me..... I don't think I really want to be creating a new ActionListener class for each JButton do I ? Is there a better way to make the JButtons created in this method visible to the actionPerformed method ?
Thanks for any help you can give me....... I'm just gettin' back into the "Swing" of things in Java.... haven't coded it for a while.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
create a single actionListener, and add it to each button.

in actionPerformed use e.getSource() to get the SKPictureButton clicked
cast e.getSource() to an SKPictureButton, and get the file associated with that button
the rest of the code in actionPerfomed is as you have it now.
I agree. Here's the link:
subject: Adding ActionListeners to JButtons
It's not a secret anymore!