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?
Yes, by adding an initializer method that returns 'this', and immediately calling that method:
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
private int anonVar;
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
// It's now here:
System.out.println("Initialized with value: " + anonVar);
}
private ActionListener init(int var){
anonVar = var;
return this;
}
}.init(myVariable) );
No 'final' declaration needed.