views:

51

answers:

2

I gave up on the GUI Builders for Java and now I develop 'em completely in code (not really very hard, with a couple of hours of practice). Now I am tackling event handling.

But I find that when I try to use a class to implement a type of listener, e.g.

private class TextAction implements FocusListener
{
   public void focusGained(FocusEvent e)
   {
       responseTxt.setText("Got focus");
   }

   public void focusLost(FocusEvent e)
   {

   }

}

I must supply an empty action handler (as above) for focusLost, even if I don't need it, or I get a nastygram from the editor saying this is not an abstract class and does not override the FocusLost method, etc.

Does this mean that action handlers must show an action handler for each event type associated with the listener, even when the action will not be used in the program?

Thanks for any help on this.

+2  A: 

The "event" system in Java is basically a hacked-on afterthought.

There's nothing special about the interfaces involved - like all interfaces, you need to implement all their methods.

If you only want to implement some of them, you can inherit from the associated Adapter class, which provides default do-nothing implementations for whatever you choose not to override.

Anon.
I wouldn't quite say its tacked on as an afterthought, its simply not part a language feature (like it is in C#).
cletus
Perhaps my wording is a little strong. What I'm really getting it is that it has no specific support from the language.
Anon.
+4  A: 

There are already base classes in the JDK for all the standard Listener interfaces. These classes implemement all the methods of the interface but do nothing in the method bodies. You get them by simply changing the interface name from XyzListener to XyzAdapter.

With these adapters you only need to override the methods you really need:

private class TextAction extends FocusAdapter
{
   @Override
   public void focusGained(FocusEvent e) 
   { 
       responseTxt.setText("Got focus"); 
   } 
}
x4u
I strongly suggest adding a @Override in there.
Tom Hawtin - tackline
Yes of course, you are right.
x4u