We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Here is all of the code with comments trying to explain a few things so it's easier to read through :)
Thanks to @TfGuy44 and @GoToLoop I have some Awesome button-code that I use frequently :D. But an error occurred when I was trying to compromise it: "Cannot refer to the non-final local variable i defined in an enclosing scope".
I use @ Override to define different results for each button and doing this works:
observasjoner = new Button(300, funcY, funcW, funcH, "s", "Observasjoner", gra, gra1, gra2 ) {
@ Override public void onClick() {
if ( observasjoner.isOver()&& !observasjoner.ignore) layout.observer = true;
}
};
But when I tried to compress 10 buttons into a for loop I got the error mentioned above. This is the problematic code:
//---Problematic code---\\
obs[i] = new Button(x, y + (i*50), funcW, plussH, "", obsN[i], pluss, pluss1, pluss2) { // ERROR
@ Override public void onClick() {
if (obs[i].isOver()&& !obs[i].ignore) println(obsN[i]);
}
};
I tried googling the error, but all I found out was that java cannot refer to non-final var accessed from inner class. I am not using a super class or extending anything, so I don't think it's relevant, but I thought I'd just mention it. I also tried writing final obs[i]
, Processing answered with expecting "class", so I tried final class obs[i]
, but that just brought more confusion...
All help is welcome.
Answers
Where did you define i?
Line 4 seems wrong
Sorry! I forgot the for-loop lol!
Line 4? The method isOver checks if the mouse is over the button and obs[i].ignore is a boolean that checks if I should ignore the button, so it have to be false for the code to run.
Contrary to JS, Java's half-baked closure cannot access non-final local variables! ~:>
They must be declared as
final
. That doesn't apply to Java 8+.However they still must behave as such: =;
Here's my mock-up, in which I declare a temporary
final
variable ii and assign current value of iterator i to it: :ar!But I've gotta warn you that it is very bad programming to force any instance of some class to access its own container! #-o
Rather than:
if (obs[ii].isOver() && !obs[ii].ignore) println(obsN[ii]);
Just go w/:
if (isOver() && ignore) println(a);
Thank you! That works perfectly!
Oh... Yeah, for some reason I have "realised" that I have to do
obs[ii].isOver().
Thanks for pointing it out :)I had no idea what you have done or haven't! I did isOver() just for the sake to have my mock-up able to run in order to test that the
final
"fix" was indeed working. :(|)I was just saying I thought I had to write the first code. I understand now that I can use the one you recommended. ;)