• Post Reply Bookmark Topic Watch Topic
  • New Topic

addActionListener(this)  RSS feed

 
Alin Andrei
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there!
First I should say what I'm trying to achieve:
I want the button's name change when the user clicks on it: from the "Press here" state into "You pressed the button!".
I've been learning JAVA for about 1 month and a half from this book: HeadFirst Java 2nd Edition by O'REILLY and I came to the point of Creating GUIs, more exactly Action Listeners!
Well, until now I know these: An event source(button, textfield,..etc) needs a Listener and I tell the button I'm his listener by this:
buton.addActionListener(new ActionListener)...
Well, this argument new ActionListener is replaced by "this", and there's no other way to add myself to be listener to the button(event source) than using "this"...the method addActionListener of the button takes a reference to an ActionListener object.
"This" refers to the current object...how else could i refer to the current object???
How else could I pass the addActionListener's argument, other than using "this"?
I don't know why it doesn't work this way!!



The only way that works with new myClass would be in something like this:




I would be very grateful if you could make the things clear to me...Thanks in advance
I'm for the very first time on this forum and I'd like to appreciate you for the "code" thing...it's just awesome and encourages us to post even more code...thanks again
PS: Omiting code for creating frame or something else was made on purpose: I didn't find it requiring for my problem

 
Campbell Ritchie
Marshal
Posts: 56197
171
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I think addActionListener(this) is an abomination against object‑orientation. It is convenient to write, but in a large application it creates a large method with so many if‑elses in, it is really difficult to maintain. It is a long time since I wrote about that, because I always refer to the old threads. Try here or here.

If you write addActionListener(this) inside a JFrame constructor or instance method, it implies that the frame is an ActionListener, by implementing the action listener interface. But frames are not intended for actions; they are intended for displaying things. Create another class, as you will find in my old posts. Of course, now that Java8 is here, you can use a λ instead, like this:-
myButton.addActionListener(evt -> myLabel.setText("Button Pressed."));

If you create a separate class, can you see from my old examples how to get the component whose text you want to change into scope?
 
Campbell Ritchie
Marshal
Posts: 56197
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to our GUIs forum.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!