JavaFX 在网格面板上交换按钮

JavaFX swapping buttons on gridpane

我正在用 JavaFX 编写益智游戏。

点击后能否将网格面板上的按钮与另一个按钮交换?

例如。我想在按下按钮 1 后交换按钮 1 和 9。 我认为应该可以更改 gridpane 上的位置。

例如,当我点击按钮 4 时,它会与按钮 9 交换。

有办法吗?

这是我的代码:

import javafx.application.Application;

import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;

import javafx.scene.Parent;

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javafx.scene.image.ImageView;


import javafx.scene.image.Image;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.layout.GridPane;

import javafx.geometry.Insets;



public class Main extends Application {

    static Scene scene1;

    @Override
    public void start(Stage primaryStage) throws Exception{

        primaryStage.setTitle("Puzzles");
        Label label1= new Label("Let's play a game");
        Button button1= new Button("Go back to the menu");
        Parent root = FXMLLoader.load(getClass().getResource("First.fxml"));
        Scene scene = new Scene(root);
        button1.setOnAction(e -> primaryStage.setScene(scene));



        GridPane gridPane = new GridPane();

        gridPane.setMinSize(800, 600);

        gridPane.setPadding(new Insets(10, 10, 10, 10));




        BufferedImage originalImgage = ImageIO.read(new File("C:\Users\PC\Desktop\mateusz\Project2\src\pic.jpg"));
        BufferedImage blank = ImageIO.read(new File("C:\Users\PC\Desktop\mateusz\Project2\src\bialt.png"));


        BufferedImage one = originalImgage.getSubimage(0, 0, 100, 100);
        BufferedImage two = originalImgage.getSubimage(100, 0, 100, 100);


        Image q1 = SwingFXUtils.toFXImage(one, null );
        Image q2 = SwingFXUtils.toFXImage(two, null );

        Image q9 = SwingFXUtils.toFXImage(blank, null );

        ImageView i1 = new ImageView(q1);
        ImageView i2 = new ImageView(q2);

        ImageView i9 = new ImageView(q9);


        Button b1 = new Button("",i1);
        Button b2 = new Button("",i2);

        Button b9 = new Button("",i9);


        gridPane.add(label1, 0, 0);
        gridPane.add(button1, 1, 0);
        gridPane.add(b1, 0, 1);
        gridPane.add(b2, 1, 1);
        gridPane.add(b9, 2, 3);



        scene1= new Scene(gridPane, 800, 600);


        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

你可以交换一个GridPane的2个children的"cells",交换两边的row/column索引:

public static void swap(Node n1, Node n2) {
    Integer temp = GridPane.getRowIndex(n1);
    GridPane.setRowIndex(n1, GridPane.getRowIndex(n2));
    GridPane.setRowIndex(n2, temp);

    temp = GridPane.getColumnIndex(n1);
    GridPane.setColumnIndex(n1, GridPane.getColumnIndex(n2));
    GridPane.setColumnIndex(n2, temp);
}

用法:

swap(b1, b9); // change places of b1 and b9