有没有其他方法可以在 JavaFX 上实现 setOnMouseClicked

Is there any other way to implement setOnMouseClicked on JavaFX

我必须在 javaFX 中创建一个矩阵。我使用 GridPane 创建它没有任何问题。接下来是在矩阵的右侧创建类似“按钮”的按钮,这些按钮会将矩阵的+1 元素向右移动。像这样:

110 <-
101 <- //ie: I clicked this button
100 <-

The result:
110 <-
110 <-
100 <-

我处理这种移位移动的方式是使用循环链表。我对此没有任何问题,我认为您可以省略该部分。我用这个方法:

private void moveRowRight(int index){
     //recives a index row and moves +1 the elements of that row in the matrix.
}

cells 是矩阵

问题在于,首先可以通过用户输入修改矩阵,即 5x5 6x6 7x7,因此按钮的数量也会发生变化。我尝试使用 BorderPane(center: gridpane(matrix), right: VBox()) 这是我在 Vbox ( 边框窗格的右侧部分 ) 并使用 setOnMouseClicked.

private void loadButtonsRight(){
        
        for(int i = 0; i < cells[0].length ; i++){
            HBox newBox = new HBox();
            
            newBox.getChildren().add(new Text("MOVE"));
            newBox.prefHeight(50);
            newBox.prefWidth(50);
            newBox.setOnMouseClicked(e -> {
                moveRowRight(i);
            }); 
            VBRightButtons.getChildren().add(newBox);  //where I add the HBox to the VBox (right part of the Border Pane)
        }
    }
}

但是接下来就是这个问题

Local variables referenced from lambda expression must be final or effectively final

看来我无法实现具有会更改的值的 lambda。有什么方法可以帮助我放置取决于矩阵大小并使用我创建的方法的“按钮”吗?

该消息告诉您解决问题所需的全部信息:

Local variables referenced from lambda expression must be final or effectively final

将您的更改变量分配给最终常量并在 lambda 中使用常量值而不是变量:

final int idx = i;
newBox.setOnMouseClicked(e ->
    moveRowRight(idx);
); 

如果您想进一步了解这一点,请参阅 baeldung 教程