每次按键需要加1-JavaFx
Need to increment by 1 every time key is pressed-JavaFx
每次我按下一个键,在这种情况下,我需要我的 p1Start 值,在这种情况下 p1StartX 递增 1。这用于 "Draw" 类型的二维数组中的路径长方形。
我的问题是,它只递增一次。我该如何解决这个问题?
scene2.setOnKeyPressed(e -> {
int p1StartX = 5;
int p1StartY = 25;
int p2StartX = 60;
int p2StartY = 25;
if (e.getCode() == KeyCode.LEFT) {
p1.setDirection(1);
p1.update();
} else if (e.getCode() == KeyCode.RIGHT) {
p1StartX++;
gameGrid[p1StartY][p1StartX].setFill(p1.getPlayerClr());
System.out.println("Player 1: Right");
}
发生这种情况是因为 p1StartX
是在您的侦听器范围内定义的。
将其移至 class 成员(静态与否 - 取决于您的设计...)- 事情将是 O.K。
此外,我很确定这适用于您定义的所有 int
值。
像这样:
//some class definition...
private int p1StartX;
//Use a constructor to init the value of p1StartX.
...
scene2.setOnKeyPressed(e -> {
....
p1StartX++;
}
每次我按下一个键,在这种情况下,我需要我的 p1Start 值,在这种情况下 p1StartX 递增 1。这用于 "Draw" 类型的二维数组中的路径长方形。
我的问题是,它只递增一次。我该如何解决这个问题?
scene2.setOnKeyPressed(e -> {
int p1StartX = 5;
int p1StartY = 25;
int p2StartX = 60;
int p2StartY = 25;
if (e.getCode() == KeyCode.LEFT) {
p1.setDirection(1);
p1.update();
} else if (e.getCode() == KeyCode.RIGHT) {
p1StartX++;
gameGrid[p1StartY][p1StartX].setFill(p1.getPlayerClr());
System.out.println("Player 1: Right");
}
发生这种情况是因为 p1StartX
是在您的侦听器范围内定义的。
将其移至 class 成员(静态与否 - 取决于您的设计...)- 事情将是 O.K。
此外,我很确定这适用于您定义的所有 int
值。
像这样:
//some class definition...
private int p1StartX;
//Use a constructor to init the value of p1StartX.
...
scene2.setOnKeyPressed(e -> {
....
p1StartX++;
}