Handling Events in Java: does it require empty event handlers
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 fin开发者_开发技巧d 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.
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");
}
}
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.
精彩评论