Wednesday, May 28, 2014

Java Listeners and Adapters, almost anonymous functions

Java allows developers to easily add listeners to different events.
e.g. button.addMouseListener(this);
However, often you don't want to implement a listener interface for your class or add an inner class
MyClass implements MouseListener
MyClass {
    private class ListenerClass implements MouseListener {
            public void mouseClicked(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            .
    }
}

With all the functions required by the interface cluttering up your code. Often you don't even need more than one or two of the functions.

Enter Adapters.
Adapters are classes which are made to match a listeners interface and only that. They do nothing when called, but the developer will override the function he needs:
button.addMouseListener( new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
    }
}


This adds flexibility to Java, almost like the anonymous functions of JavaScript.

Source: https://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters
http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

No comments:

Post a Comment