我有一个带有按钮correctBut和标签Label pointsLbl = new Label("0")的简单窗口。我希望每次我按下按钮时,pointsLbl的文本都会改变。最初,pointsLbl的文本是"0“。然后,当我按下按钮时,应该是"1";
因此,我创建了一个额外的变量int points,它最初也是0。我认为我可以在points中添加+1,而不是将其转换为string,并将其设置为新文本。
String newValStr = points.toString();
pointsLbl.setText(newValStr);但是我得到了以下错误:“变量点是从内部类中访问的,需要是最终的或实际上是最终的”。
因此,应该如何编写代码,以便我可以更改值,然后将setText更改为pointsLbl。
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class QuickGameWindow {
public static void display() {
Stage window = new Stage();
int points = 0;
String parsedPoints = "";
window.setTitle("New Window");
GridPane grid = new GridPane();
grid.setPadding(new Insets(10,10,10,10));
grid.setVgap(20);
grid.setHgap(10);
Button correctBut = new Button("Correct");
Label textLbl = new Label("Points - ");
Label pointsLbl = new Label("0");
correctBut.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
//Here comes the problem. I cannot change the value of points.
points++;
String newValStr = points.toString();
pointsLbl.setText(newValStr);
}
});
GridPane.setConstraints(correctBut, 3, 3);
GridPane.setConstraints(pointsLbl, 1, 5);
GridPane.setConstraints(textLbl, 3, 5);
grid.getChildren().addAll(correctBut,pointsLbl,textLbl);
Scene scene = new Scene(grid, 300, 200);
window.setScene(scene);
window.show();
}
}发布于 2016-05-15 18:22:06
在对事件处理程序使用lambda表达式时,外部作用域中定义的所有变量都必须是最终变量或成员变量。这给你留下了两个选择:
1)使计数器points成为成员变量:
private int points = 0;2)使用区域设置IntegerProperty而不是int:
IntegerProperty points = new SimpleIntegerProperty(0);
...
correctBut.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
points.set(points.get() + 1);
String newValStr = points.toString();
pointsLbl.setText(newValStr);
}
});https://stackoverflow.com/questions/37241933
复制相似问题