Reputation: 33
I'm writing a puzzle game in JavaFX.
Can you make a button swap on a gridpane with another button after clicking it?
Ex. I want to swap button number 1 and 9 after i press button 1. I think it should be possible to change place on gridpane.
Ex when I click on button 4 it swaps with button 9.
Is there a way to do it?
Here is my code:
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);
}
}
Upvotes: 1
Views: 1145
Reputation: 82451
You can swap the "cells" of 2 children of a GridPane
by exchaning the row/column indices of both nodes:
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);
}
Usage:
swap(b1, b9); // change places of b1 and b9
Upvotes: 4