Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding event listeners in java

I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};

or:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)

like image 415
Mascarpone Avatar asked Feb 24 '26 07:02

Mascarpone


1 Answers

Normally defining a class, instantiating an instance, and then using that instance are done separately:

class MyListener extends OnClickListener {
    public void onClick(View v) {
        // my onClick code goes here
    }
}

MyListener foo = new MyListener();

button.setOnClickListener(foo);

But sometimes you need a subclass that you will instantiate only once immediately, which is often the case for event handlers. It is convenient to define it and instantiate it together using an anonymous (inner) class:

OnClickListener foo =
    new OnClickListener() {
        public void onClick(View v) {
            // my onClick code goes here
        }
    };

button.setOnClickListener(foo);

But since foo is only used once, we can takes this one step further and eliminate the local variable foo as well, so:

button.setOnClickListener(foo);

can be formatted as:

button.setOnClickListener(
    foo
);

substitute in the value of foo:

button.setOnClickListener(
    new OnClickListener() {
        public void onClick(View v) {
            // my onClick code goes here
        }
    }
);

reformatted again without some much whitespace to see it as it is often written:

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // my onClick code goes here
    }
});

I think this last format hurts readability. I format my anonymous classes similar to how it is in the next to last format - the better readability (IMHO) is worth a little extra whitespace.

like image 190
Bert F Avatar answered Feb 26 '26 21:02

Bert F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!