Question

My class Piece extends JPanel The Board is set on a GridLayout.

my problem is i want to put a piece on a x3 y3 of the board. I add it but i cannot see the piece.

this is my code:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.EtchedBorder;

public class Board extends JPanel{
private static final String imageFolderPath = "src/resources/images/";
Dimension dimension = new Dimension(500, 500);
JPanel board;
JLabel piece;
MovePiece mp = new MovePiece(this);

public Board(){
     //set size of panel;
     this.setPreferredSize(dimension);
     this.addMouseListener(mp);
     this.addMouseMotionListener(mp);

  //create the Board
  board = new JPanel();
  board.setLayout(new GridLayout(9,7));
  board.setPreferredSize(dimension);
  board.setBounds(0, 0, dimension.width, dimension.height);
  this.add(board);

  JPanel [][] square = new JPanel[7][9];

  for(int x = 0; x<7; x++){
        for(int y = 0; y<9; y++){
          square[x][y] = new JPanel();
          square[x][y].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
          square[x][y].setBackground(new Color(185, 156, 107));
          board.add(square[x][y]);
     }
  }

  ImageIcon icon = new ImageIcon(imageFolderPath+"/pieces/blank.png");
  Piece orb =new Piece("Orb", "borb.png", "none", "none", 1, 'b', 0, 3, 7, icon);
  square[3][3].add(orb);

} }

Was it helpful?

Solution

There are, at least, two things that stand out...

Firstly:

private static final String imageFolderPath = "src/resources/images/";

It's unlikely that the directory src will exist once the application is built.

Second:

ImageIcon icon = new ImageIcon(imageFolderPath+"/pieces/blank.png");

ImageIcon(String) denotes that the reference resource is a file on the file system. Based on the value of imageFolderPath this doesn't seem your likely intention. Instead, it seems you are trying to use these images as embedded resources, in which case you should be using something more like...

ImageIcon icon = new ImageIcon(getClass().getResource("/resources/images/pieces/blank.png"));

Personally, I would use ImageIO instead, at least this will throw an IOException if the image can't be loaded...

try {
    BufferedImage img = ImageIO.read(getClass().getResource("/resources/images/pieces/blank.png"));
    ImageIcon icon = new ImageIcon(img);
    // update UI
} catch (IOException exp) {
    exp.printStackTrace();
    // Probably show a message and exit...
}

Bonus issue:

Without seeing Piece, it's possible that you are not providing appropriate size hints or adding anything to it or using a null layout...or something else that we can't identify...

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