Hidden Hidden - 7 months ago 23
Java Question

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?

Answer

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