Forums Register Login

New to GUI, need help with actionListener and buttons

+Pie Number of slices to send: Send
I'm trying to use the same actionlistener for multiple buttons (two to start with). Here is my code:


Is there any way I can tell which button was pressed in the actionPerformed method? Instead of the way I'm doing it just now. I don't want to have to add an if statement for every button I create, I've been looking around for a while but can't seem to find anything.
Thanks in advance..
+Pie Number of slices to send: Send
Better to use the getSource() method (this compares against the instance and not string values):

+Pie Number of slices to send: Send
Hi Foamy Caramel,

I think you should use a common action listener if all the buttons do the same thing, regardless of buttons.
I prefer using separate action listeners for each buttons, and wrap the common things into a method.
+Pie Number of slices to send: Send
There are 2 ways of implementing ActionListener:

Option 1: To have common ActionListener Implemented


OPTION 2: To have individual actionlisteners


See which one is better for you. Both approaches have same end-results.

Thanks.
+Pie Number of slices to send: Send
The version with one listener and getSource() is by no means object-oriented programming, even though you see it in many books.
I brought this back from the farm where they grow the tiny ads:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 5618 times.
Similar Threads
Swing and Thread nightmare. Please help.
JButton button
How to add two buttons in each row?
code error
how to get paintComponent to respond to a variety of events
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 09:59:16.