This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm currently trying to write a simple Swing app that grabs strings from a few JTextFields when a JButton is pushed, parses the strings for doubles, does some computations and spits the answer out into another JTextField. The logic is trivial but I'm new to swing and am having problems accessing the contents of the JTextFields. Here's what I have so far:
The only way I know of to get the button action event is the anonymous class around the area of line 25 (I currently have this area doing the iteration and print just so that I could test the button). If I try to get the information from the fields here and pass it to the method at line marked 43 I get this error: "cannot refer to a non final variable inside an inner class defined in a different method." Ok, that makes sense. However if I just try to call the doCalc method from line 25 I get a "variable cannot be resolved" error when I try to refer to any of my JTextFields from that method. It seems like my issue is that I don't know how to bring those field's pointers into my doCalc method's namespace but I'm not sure how to implement this. Hints please?
[ June 23, 2008: Message edited by: Tristan Rouse ] [ June 23, 2008: Message edited by: Tristan Rouse ]
This is not really a Swing problem as such but just a problem with anonymous classes.
You'll either need to declare your JTextFields as final (as the error suggests) or turn them into instance variables. The same would go for i, but since you're changing its value making it final is not an option.
I'll admit I wasn't exactly sure where this post should go. Also, the reason I didn't try simply making the JTextFields final was that I was under the naive assumption that that somehow make the object (and all its variables including text) final. Making a reference variable final just means that you cannot say:
is that correct? [ June 23, 2008: Message edited by: Tristan Rouse ]
That's the most obvious reason for using final. Another is that it allows you to use those variables in anonymous classes.
Also, the final modifiers only refers to variables, not objects themselves. The objects can still change their internals, and the variables also just will disappear (go out of scope) when the method ends. After that the object is eligible for garbage collection if that was the only reference.
The advantage with anonymous classes is, that the class now knows exactly which object it should use. As such, the class itself will keep a reference to the object - and that's just what you want.