This has nothing to do with Swing, nothing at all. You should show your code that has an example of this, but likely you are using an inner class, possibly an anonymous inner class, and if you use these and try to use variables inside the inner class that are local to an enclosing method (or other block such as a constructor), then you are requried to make these variables final or promote them to class fields. Again this is a Java requirement, not a Swing requirement.
A Swing example:
public MyConstructor() {
final int localIntVar = 3; // this must be final
myJButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// because you use the local variable inside of an anon inner class
// not because this is a Swing application
System.out.println("localIntVar is " + localIntVar);
}
});
}
and a Non-Swing example:
public void myMethod() {
final String foo = "Hello"; // again it must be final if used in
// an anon inner class
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(foo);
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}).start();
}
There are several tricks to avoid this:
- Promote the variable to a class field, giving it class scope.
- Have the anonymous inner class call a method of the outer class. But then, the variable will still need to have class scope.
Edit 2
Anthony Accioly posted an answer with a great link, but then for unknown reasons deleted his answer. I'd like to post his link here, but would love to see him re-open his answer.
Cannot refer to a non-final variable inside an inner class defined in a different method