如何在JavaFx中单击按钮时更改变量 [英] How to change a variable when a button has been clicked in JavaFx
问题描述
当我单击JavaFX中的按钮时,我想要更改变量。但是当我尝试使用程序中的变量时,它表示
I want change a variable when I click a button in JavaFX. But when I try to use the variable from the program it says
从lambda内部引用的局部变量必须是final或者有效的final。
local variables referenced from inside a lambda must be final or effectively final.
我无法使其成为最终,因为我需要更改它以便我可以使用它。我的代码看起来像这样
I can't make it final though because I need to change it so I can use it. My code looks like this
Button next = new Button();
next.setText("next");
next.setOnAction((ActionEvent event) -> {
currentLine++;
});
我能做些什么来解决这个问题?
what can i do to get around this?
推荐答案
概念
内部使用的所有局部变量类
应该是 final或者有效的最终
,即状态一旦定义就不能改变。
All the local variables used inside annonymous inner classes
should be final or effectively final
i.e. there state cannot change once defined.
原因
内部类无法引用的原因非final
局部变量是因为本地类实例即使在方法返回后也可以保留在内存中,并且可以更改使用的变量值,导致同步
问题。
The reason inner classes cannot reference non final
local variables is because the local class instance can remain in memory even after the method returns and can change the value of the variable used causing synchronization
issues.
你如何克服这个?
1 - 宣布一个为你完成工作并在动作处理程序中调用它的方法。
1 - Declare a method which does the job for you and call it inside the action handler.
public void incrementCurrentLine() {
currentLine++;
}
稍后再拨打:
next.setOnAction((ActionEvent event) -> {
incrementCurrentLine();
});
2 - 声明 currentLine
为 AtomicInteger 。然后使用其 incrementAndGet()
增加值。
2 - Declare currentLine
as AtomicInteger. Then use its incrementAndGet()
to increment the value.
AtomicInteger currentLine = new AtomicInteger(0);
AtomicInteger currentLine = new AtomicInteger(0);
稍后,你可以使用:
next.setOnAction((ActionEvent event) -> {
currentLine.incrementAndGet(); // will return the incremented value
});
3 - 你也可以声明一个自定义类,在其中声明方法并使用它们。
3 - You can also declare a custom class, have methods declared in it and use them.
这篇关于如何在JavaFx中单击按钮时更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!