Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Swing / AWT / SWT and the fly likes The best approach for event listener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "The best approach for event listener" Watch "The best approach for event listener" New topic

The best approach for event listener

Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

Hi ranchers.
in swing application, we have the "event listeners".
we developing my application , I used :
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// some code
but borland used the following approach in thier JBuilder :
myButton.addActionListener(new Manager_myButton_actionAdapter(this));
then :
void myButton_actionPerformed(ActionEvent e) {
// some code here
then , in the same java file, they create a new class :
class Manager_myButton_actionAdapter implements ActionListener {
Manager adaptee;
Manager_myButton_actionAdapter(Manager adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
so is the best approach ? and what is the approach that is used in the real applications ?
(Borland is a big company and has a long history with IDEs , so should I used their approach?)
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

It depends on what you are trying to do, but personally, the first version is much more readable, and should be OK to use in the majority of circumstances. Probably the *worst* designed GUIs I have seen have been from the code created through visual GUI creators, so I would definately not try to learn good coding habits from code generation tools. This design just probably makes it easier for the GUI design tool to keep track of what listeners go with what buttons.

The only times you might want to not use the anonymous ActionListener defined in place would be if you need to reuse the ActionListener somewhere else. It's also possible to run into performance problems by defining so many small classes, but I've really never seen this to be an issue in any of the code I've worked on... you'd probably have to have millions of anonymous ActionListners for this to be a real problem.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I agree. Here's the link:
subject: The best approach for event listener
It's not a secret anymore!