Hidden
Hidden

Reputation: 101

Passing current class in constructor, inside actionlistener

So I'm trying to pass the current class inside a constructor of an actionlistner

something like this:

    public ActionListener createTaskListener() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                CreateTask ct = new CreateTask();
                CreateTaskController ctc = new CreateTaskController(ct, mod.getAssessments(), this); 
                // but it says anonymous actionlistener 
                ctc.loadDataToTaskView();
                ct.setVisible(true);
            }
        };

    }

What is the general approach for a problem like this? Or is this just shoddy code?

Upvotes: 1

Views: 322

Answers (2)

suulisin
suulisin

Reputation: 1435

this within an inner class refers to the inner class instance. To refer to the enclosing class instance, you can use OuterclassName.this.

For example

public ActionListener createTaskListener() {
    return new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            CreateTask ct = new CreateTask();
            CreateTaskController ctc = new CreateTaskController(ct, mod.getAssessments(), YourClassName.this);
            // but it says anonymous actionlistener
            ctc.loadDataToTaskView();
            ct.setVisible(true);
        }
    };
}

Upvotes: 0

Jorn Vernee
Jorn Vernee

Reputation: 33905

this will point to the anonymous instance of the action listener. If you want to pass the this pointer of the enclosing class, use <enclosingClassName>.this.

e.g.:

class MyClass {
    public ActionListener createTaskListener() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                ...
                CreateTaskController ctc = 
                    new CreateTaskController(ct, mod.getAssessments(), MyClass.this); // <-
                ...
            }

        };

    }
}

As a side note. ActionListener is a functional interface. So you could simplify your code with a lambda expression:

class MyClass {
    public ActionListener createTaskListener() {
        return ae -> {
            CreateTask ct = new CreateTask();
            CreateTaskController ctc = 
                new CreateTaskController(ct, mod.getAssessments(), MyClass.this);

            ctc.loadDataToTaskView();
            ct.setVisible(true);
        };    
    }
}

Upvotes: 4

Related Questions