对最终变量和有效最终变量的JavaFX事件处理
下面是代码片段的一部分:对最终变量和有效最终变量的JavaFX事件处理,java,javafx,Java,Javafx,下面是代码片段的一部分: for (int col=1;col<=7;col++) { for (int row=2;row<=31;row++) { if (col!=4) { b = new Button(); b.setText(Seat.calcID(row, col)); b.setMinSize(2, 2); b.setFont(new Font(8))
for (int col=1;col<=7;col++) {
for (int row=2;row<=31;row++) {
if (col!=4) {
b = new Button();
b.setText(Seat.calcID(row, col));
b.setMinSize(2, 2);
b.setFont(new Font(8));
addableSeat.change(x, row, col);
System.out.println(row+" "+col);
b.setOnAction(e->{
book.addSeat(Seat.genSeat(x, row, col));
System.out.println(">>>"+addableSeat.accessId()+"<<<");
});
no=(col>4)?col+1:col;
grid.setConstraints(b,no,row);
grid.getChildren().add(b);
}
}
}
for(int col=1;col4)?col+1:col;
grid.setConstraints(b,no,row);
grid.getChildren().add(b);
}
}
}
有一个错误指出eventhandler中的变量“row”和“col”必须是final或实际上是final。我怎样才能做到这一点
如果您需要额外的代码片段,我愿意提供。谢谢 这是因为
行
和列
的值预计会随着时间的推移通过行++
和列++
发生变化,因此编译器知道它既不是最终的
,也不是有效的最终的
解决这个问题的唯一简单方法(我能想到的)是声明额外的局部变量
final int r = row;
final int c = col;
b.setOnAction(e->{
book.addSeat(Seat.genSeat(x, r, c));
System.out.println(">>>"+addableSeat.accessId()+"<<<");
});
final int r=行;
最终int c=col;
b、 设定动作(e->{
书加座(座加座(x,r,c));
System.out.println(“>>>”+addableSeat.accessId()+”在大多数情况下,采用的是。
在某些情况下,您可能更愿意将行
和列
声明为类变量(字段):
private int行,列;
对于(col=1;col)另一个选项是将row
和col
声明为类变量(字段)。@c0der是的,这基本上是包装器方法,对于如此简单的上下文来说太复杂了。只有在需要“写访问”时才可以使用。"既然您已经给出了答案,您可能会使它更完整。例如,您可以使用IntegerProperty
来包装每个行
和列
。还可以提到,当您需要更改匿名类或lambda表达式的值时,使用此方法非常有用。@Jai感谢您的输入。请您将其添加到您的答案中以使其更完整?(我不确定是否仅为此使用IntegerProperty
)。我认为您的答案在大多数情况下都是正确的方法。
final IntegerProperty col = new SimpleIntegerProperty();
final IntegerProperty row = new SimpleIntegerProperty();
for (col.set(1);col.get()<=7;col.set(col.get()+1)) {
for (row.set(2);row.get()<=31;row.set(row.get()+1)) {
if (col.get()!=4) {
...
...
b.setOnAction(e->{
book.addSeat(Seat.genSeat(x, row.get(), col.get()));
// I can even change value from the handler
row.set(Integer.MAX_VALUE);
});
}
}
}
private int row, col;
for (col=1;col<=7;col++) {
for (row=2;row<=31;row++) {
if (col!=4) {
...
...
b.setOnAction(e->{
book.addSeat(Seat.genSeat(x, row, col));
});
}
}
}