繁体   English   中英

有没有其他方法可以在 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 (边框窗格的右侧)内添加一些 HBox 并使用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 的值会发生变化。 有什么方法可以帮助我放置取决于矩阵大小并使用我创建的方法的“按钮”?

只需声明一个最终值并使用它。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM