bluevoxel
bluevoxel

Reputation: 5358

EventHandler implemented as an anonymous inner class

I wan't to use keyword this in refer to my main class in the EventHandler block, say:

public class Extra {

    private SuperObject object;

    public Extra() {

        Button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent ae) {

                object = new SuperObject(this);
            }
        });
    }
}

// where...

public class SuperObject {

    public SuperObject(Extra e) {

        // something
    }
}

But in this case I've got an warning about that I haven't declare a constructor for the SuperObject class with ActionEvent parameter in it. What can I do in such situation?

Upvotes: 0

Views: 1224

Answers (3)

James_D
James_D

Reputation: 209358

Since you're using Java 8, in addition to the other solution(s) posted, you can also replace the inner class with a lambda, in which this has its intuitive meaning (a reference to the surrounding object):

button.setOnAction(ae -> {
    object = new SuperObject(this);
});

Upvotes: 4

keuleJ
keuleJ

Reputation: 3486

You have to do it like this

object = new SuperObject(Extra.this);

Upvotes: 2

SLaks
SLaks

Reputation: 887453

this is your anonymous inner EventHandler class.

To access the outer this, use Extra.this.

Upvotes: 3

Related Questions