1

I'm writing a small GUI program for playing Chess. I have stumbled upon the problem that I can't add any elements to chessTable without the program returning an InvocationTargetExcepetion. Here is my code:

public void start(Stage primaryStage) throws Exception {
    GridPane chessTable = new GridPane();
    chessTable.getStylesheets().add(getClass().getResource("styles.css").toString());
    Box chessBox = new Box(112 , 94, 0);
    chessBox.getStyleClass().add("chess-box");
    for (int h = 0; h < 8; h++) {
        for (int w = 0; w < 8; w++) {
            GridPane.setConstraints(chessBox, w, h);
            chessTable.getChildren().add(chessBox);

        }
    }
    primaryStage.setTitle("ChessGame");
    primaryStage.setFullScreen(true);
    Scene scene = new Scene(chessTable, 900, 750);
    primaryStage.setScene(scene);
    primaryStage.show();
}
  • What are your imports? You may be trying to add a swing box rather than a JavaFX box. – M. Goodman Feb 11 '19 at 21:33
  • In the future, include the full [stack trace](https://stackoverflow.com/questions/3988788/). The `InvocationTargetException` should never be the root problem; look at the `Caused by:`s to see what's _really_ the error. – Slaw Feb 12 '19 at 01:52

1 Answers1

0

Try something along these lines(eg. I don't know where your "styles.css" resides ...) :

    public void start(Stage primaryStage) throws Exception {
        GridPane chessTable = new GridPane();
        chessTable.getStylesheets().add(getClass().getResource("/styles.css").toString());
        for (int h = 0; h < 8; h++) {
            for (int w = 0; w < 8; w++) {
                Box chessBox = new Box(112, 94, 0);
                chessBox.getStyleClass().add("chess-box");
                GridPane.setConstraints(chessBox, w, h);
                chessTable.getChildren().add(chessBox);

            }
        }

Note that it creates a new Box for every cell in oposite to your code, that tries to put the same box in different cells at the same time(can only add it once).

kai
  • 894
  • 1
  • 7
  • 15