Is it possible to pass parameters, or access external parameters to an anonymous class? For example:
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
}
});
Is there any way for the listener to access myVariable or be passed myVariable without creating the listener as an actual named class?
Technically, no, because anonymous classes can’t have constructors.
However, classes can reference variables from containing scopes. For an anonymous class these can be instance variables from the containing class(es) or local variables that are marked final.
edit: As Peter pointed out, you can also pass parameters to the constructor of the superclass of the anonymous class.