Understanding event listeners in java

I am new to java and am still trying to understand the language, so I apologize if this question may sound noobish.

Something I don’t understand about listeners, someday you can see a listener declared this way:

    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();
            }
        });

What puzzles me the most is that it is a semicolon and parentheses after the end of the method.

I understand inner classes with the goal of having multiple listeners, but I don't understand this mixed declaration of variables and methods.

What purpose does he have?

How is this announced?

WTF ?: P

cheers :)

+3
source share
6 answers

Typically, class definition, instance creation, and subsequent use of this instance are performed separately:

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

MyListener foo = new MyListener();

button.setOnClickListener(foo);

, , . () :

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

button.setOnClickListener(foo);

foo , foo, :

button.setOnClickListener(foo);

:

button.setOnClickListener(
    foo
);

foo:

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

- , , :

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

, . , , - (IMHO) .

+3

...

javax.swing.SwingUtilities.invokeLater(Runnable runnable);

invokeLater() SwingUtilities, Runnable .

; , ?

- Runnable . , :

Runnable parameter = new Runnable() 
{
    public void run() 
    {
        createAndShowGUI();
        }
    }
};
+2

. , Java. , , Runnable, : -

public class YourRunnableClass implements Runnable {
   public void run() {
      ...
   }
}

, :

javax.swing.SwingUtilities.invokeLater(new YourRunnableClass());

P/S: "WTF" .:)

+2

. . , !

+1

. .

, , .

PS. , , , .

+1

.

invokeLater , Runnable.

, :

class Example implements Runnable{
  public void run(){
    // do something
  }
}

:

javax.swing.SwingUtilities.invokeLater(new Example());

But since this Example class is likely to be used only once, it is more convenient to use an anonymous class.

+1
source

Source: https://habr.com/ru/post/1787164/


All Articles