• Post Reply Bookmark Topic Watch Topic
  • New Topic

ActionListenr explanation  RSS feed

 
Cornelius Flavius
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I totally don't understand what that code means. Can someone give the most simple example, cracked into most lines possible? All I get it is that you add listener to a button (or some other component) and somehow (but where) get a response:




I suppose it should return some event, which will make possible to write a method that would work depending on the action passed, as in:


 
Vincent Tyson
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
actionListener waits for an event to happen before it continues, in this modest example, when you run the program you will see the program asks for user input and then continues with the program.

Feel free to use segments of this code for your own work if it can be helpful.



You could add a function for the hover command and have it display "click me" for example.
 
Campbell Ritchie
Marshal
Posts: 56221
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good grief! Who taught you that sort of code? Please tell us where you found that code, so we can be sure there isn't a breach of copyright. I am pretty sure I have seen that code before somewhere.

I have remembered where I last saw it. I told you it was dreadful then and I am telling you it is dreadful now. The worst bit is making the frame a listener. You are now moving out of the realms of object‑oriented programming (or for Java8, functional programming). If you have two buttons you will end up with a horrible mess of nested if‑elses. Each button should have it own listener and each listener should be an object (or in Java8 maybe a function).

Read this thread and the links therein for a longer discussion about listeners.
Also find out about Actions (and the AbstractAction class); Actions are similar to action listeners but probably better.
If you use Java8, find out about using a λ instead of an anonymous class.

Moving this discussion to our GUIs forum.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!