gpt4 book ai didi

JavaFX 在网格面板上交换按钮

转载 作者:行者123 更新时间:2023-11-29 08:22:25 25 4
gpt4 key购买 nike

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

单击后能否使网格 Pane 上的按钮与另一个按钮交换?

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

例如,当我点击按钮 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 个子节点的“单元格”:

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

关于JavaFX 在网格面板上交换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com