简体   繁体   中英

Is there any other way to implement setOnMouseClicked on JavaFX

I had to create a matrix in javaFX. I created it without any problem with GridPane. The next thing is to create like "buttons" on the right side of the matrix, these buttons will move +1 element of the matrix to the right. Like this:

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

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

The way I handle this bit-shifting-moving was with circular linked list. I don't have any problem with that I think you can ommit that part. I use this method:

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

cells is the matrix

The problem is that, first the matrix can be modified by the user input ie 5x5 6x6 7x7, so the number of buttons will also change. I tried using a BorderPane(center: gridpane( matrix ), right: VBox()) and this is the part of the code how I added some HBox inside the Vbox ( right part of the border pane ) and using the 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)
        }
    }
}

But then there's this problem.

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

It seems that I cannot implement lambda with a value that will change. Is there any way to help me to put "buttons" that depends of the matrix size and that uses the method I've created?

Just declare a final value and use it.

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

If you wish to understand this more, see the baeldung tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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