Computer Science Canada

[Tip] Implementing Listeners

Author:  wtd [ Sat Nov 25, 2006 5:46 pm ]
Post subject:  [Tip] Implementing Listeners

Ok, I'm getting annoyed enough at seeing this that I can't help but post something about it.

When you have distinct controls in your app, please, for the love of everything sacred, do not have your container implement ActionListener.

What do I mean by this?

Well, avoid a situation like:

code:
class Window extends JFrame implements ActionListener {
   private JButton greetButton;
   private JTextField nameEntryTextField;

   // ...

   public void actionPerformed(ActionEvent e) {
      if (e.getSource() == greetButton) {
         String inputName = NameEntryTextField.getText();

         if (!inputName.equals("")) {
            System.out.println("Hello, " + inputName + "!");
         }
      }
   }
}


Instead, use anonymous inner classes to clear this up.

code:
class Window extends JFrame {
   private JButton greetButton;
   private JTextField nameEntryTextField;

   public Window() {
      // setup stuff...

      greetButton = new JButton("Greet!");
      greetButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String inputName = nameEntryTextField.getText();

            if (!inputName.equals("")) {
               System.out.println("Hello, " + inputName + "!");
            }
         }
      });
   }
}

Author:  Regeane [ Mon Dec 04, 2006 1:13 pm ]
Post subject: 

please excuse if this is ignorance, but what is the benefit to the inner class rather than implementing?

Author:  wtd [ Mon Dec 04, 2006 1:18 pm ]
Post subject: 

Imagine you have ten things that respond to actions in your GUI. Now, ask yourself if you want to have a ten-way conditional branch. Smile

Author:  Regeane [ Mon Dec 04, 2006 2:11 pm ]
Post subject: 

what if you only had one condition? is it still better to do it that way, or does it really matter?

Author:  Aziz [ Fri Dec 08, 2006 8:51 am ]
Post subject: 

Just remember, there's sometimes problems accessing things from inside an inner class. for example, 'this' would refer to the anonymous class, NOT the main class. Also, I've run into errors saying a member has to be declared final, or some such. I usually call a method from inside this if it's a big deal, (such as importing files). Something simple (like disabling a button) usually resides in the inner class, for me.


: