Question

I'm in the process of developing a chessboard, with an issue. I'm trying to use an image to represent a chess square. But the image isn't showing.

This is the code in question:

//Add a chess board to the Layered Pane 
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);

for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );

int row = (i / 8) % 2;
if (row == 0); 
JLabel panel = new JLabel(new ImageIcon("/Users/Downloads/pieces/EmptySquare.jpg") ); 
}

All that's being shown are pieces and no squares, thanks in advance.

Was it helpful?

Solution

Two things...

First...

Your if statement is ending in ;

if (row == 0); 

This is effectively ignoring the statement altogether.

Second, you never seem to add the panel to the UI...

    //...
    JLabel panel = new JLabel(new ImageIcon("/Users/Downloads/pieces/EmptySquare.jpg") ); 
} // End of for-loop...

Consider using ImageIO.read instead of ImageIcon as it will provide more details if the image can't be loaded. Take a look at Reading/Loading an Image for more details...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top