So I am trying to display a chessboard in Java. So far, I can correctly draw and color a bunch of rectangles and have the window and rectangles resize properly. However, now i want to add an image of a chess piece on top of those rectangles, and I am not sure how to proceed.
I create an imageview of a png for a chess piece, but when I try adding it to the gridpane like i did the rectangles, it gives me a duplicate child error.
Here is the code that works so far
package test3;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.image.*;
/**
*
*/
public class Test3 extends Application {
GridPane root = new GridPane();
final int size = 8;
ImageView pawn = new ImageView("file:pawn.png");
@Override
public void start(Stage primaryStage) throws Exception {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
Rectangle square = new Rectangle();
Color color;
if ((row + col) % 2 == 0) {
color = Color.CHOCOLATE;
}
else {
color = Color.ANTIQUEWHITE;
}
square.setFill(color);
root.add(square, col, row);
square.widthProperty().bind(root.widthProperty().divide(size));
square.heightProperty().bind(root.heightProperty().divide(size));
}
}
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
What would be the best way to create an imageview of a chess piece and draw it on top of the rectangles, like how chess pieces are on a board? I already have a file, say pawn.png, i can make an imageview of it, but any time i try to add the image view to the gridpane where i drew rectangles, it gives errors. I am not sure what to do. I tried having a second gridpane where i only add the images, but that also gives duplicate child errors.
