user2154826
user2154826

Reputation:

Passing a method as parameter

I'm trying to pass a method as parameter. How to do it?

I have this in mind:

public class MyButton extends JButton{

public MyButton(){
    super();
}

public void setClick( method() );
{
this.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent arg0) {
                method();
            }
            public void mouseEntered(MouseEvent arg0) {}
            public void mouseExited(MouseEvent arg0) {}
            public void mousePressed(MouseEvent arg0) {}
            public void mouseReleased(MouseEvent arg0) {}
        });
}

Upvotes: 2

Views: 206

Answers (4)

Alex Adas
Alex Adas

Reputation: 210

You cannot do it in java like in C#. In java you you need to define interface and pass it as parameter. Last say interface SetClickInterface{ void setClick(); }

    public class MyClass extends JButton{
    private SetClickInterface clickMethod;

public void setSetClickInterface (SetClickInterface click) { this.clickMethod= click; } { this.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { if(clickMethod != null) { clickMethod.setClick(); } } public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} }); } </pre>

Upvotes: 0

arataj
arataj

Reputation: 373

You can use lambdas from Java 1.8, an "early access" version is available at https://jdk8.java.net/lambda/

Upvotes: 3

harsh
harsh

Reputation: 7692

You can only pass objects or primitives in Java, passing functions as parameter in java isn't possible

Upvotes: 0

duffymo
duffymo

Reputation: 308733

You can either pass a JavaScript function and execute it using Rhino in Java 7 or create a Command interface and pass instances of it. Java doesn't have function objects outside of classes.

public interface Command {
    void execute();
}

Or you can pass either a Runnable or Callable implementation of your choice.

Upvotes: 4

Related Questions