Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to Handle Events?  RSS feed

 
Jaime Shaker
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone
As a junior programmer, I'm not quite sure which is the better way to handle gui events.
I have seen examples that use inner classes and others implement listeners.
Which is the best practice?
How are events handled in "real world apps"?
Thanks
Jaime
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jaime
I'm new at this myself but it seems to me that it mostly a matter of preference and what makes the code easier to read. If you just have a couple of components that need to handle events it is probably easier and more readable to use an annonymous inner class. On the other hand if there a lot of buttons or other components that need event handling then it is probably easier to group them all in a separate inner class and use the getSource() method to handle the events for each component.
This is all assuming that there is no performance hit one way or the other (I don't think there is).
If it's a really large app you amy even want to create a top level class that you just use instances of in your other classes to handle the events.
If I'm wrong or misguided someone a little more experienced can probably shed a little more light on this.
hope that helps
Dave
 
Aleksey Matiychenko
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even handling in Java 2 is done using event listeners. You have several options for using them.
1. Use an anomyous listener for every button
i.e. ( jbutton1.addActionListenr(new ActionListener(){
public void actionPerformed(ActionCommand C)
{
System.out.println("Hello World");
}
});
2. Create one listener that checks for either a source or a message command using getSource() or getMessageCommand() respectively.
3. Use "Command" pattern (read the Gang of 4 book on design patterns of Java Design Patterns book.


 
Jaime Shaker
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, appreciate the help!
Also, thanks for the tip about the "Command" pattern.
Everyday pattern examples are what makes them sink in.
Jaime
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!