-1
    public void updateBoard() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                Piece piece = game.getBoard().getPiece(i, j);
                if (piece != null) {
                    String name = piece.getName();
                    boolean isWhite = piece.isWhite();
                    String color = (isWhite) ? "white" : "black";
                    ImageIcon icon = new ImageIcon(
                            getClass().getResource("/resources/pieces/" + color + name + ".png"));
                    System.out.println("Image load status: " + icon.getImageLoadStatus());
                    if (icon.getImageLoadStatus() != MediaTracker.COMPLETE) {
                        System.out.println("Failed to load image for " + color + " " + name);
                    }

                    boardButtons[i][j].setIcon(icon);
                } else {
                    boardButtons[i][j].setIcon(null);
                }
            }
        }
    }

I am trying to display a chess board but when I attempt to load icons onto the chess board it doesnt display anything, the console is completely empty, no errors no system messages. Why could this be happening? I have check 100 times to make sure the file names are correct.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Try to remove "/resources" from the image path – Seb Perp Jun 10 '23 at 06:10
  • The directory containing the files needs to be defined on your classpath. – camickr Jun 10 '23 at 13:44
  • I suggest reading the [official tutorial on ImageIcon](https://docs.oracle.com/javase/tutorial/uiswing/components/icon.html), specifically the hint "If the data location is invalid (but non-null), an ImageIcon is still successfully created; it just has no size and, therefore, paints nothing. As shown in the createImageIcon method, it is advisable to first verify that the URL points to an existing file before passing it to the ImageIcon constructor. " – Hulk Jun 10 '23 at 14:03
  • You might want to look at other questions like https://stackoverflow.com/questions/1464291/how-to-read-text-file-from-classpath-in-java and https://stackoverflow.com/questions/2343187/loading-resources-using-getclass-getresource – Progman Jun 11 '23 at 08:02

1 Answers1

0

One of the ImageIcon constructors takes a String as a parameter.

Just assure the path is relative, so remove the initial slash character.

ImageIcon icon = new ImageIcon("resources/pieces/" + color + name + ".png");
Reilas
  • 3,297
  • 2
  • 4
  • 17