I'm making a board game in Java, and I am trying to render the board itself in JPanel. The way I'm trying to do this is by inserting a image of the board (which is represented by a JLabel) and a grid (which is also represented by a JPanel). The idea is for each grid square to correspond to the squares on the image of the board.
Here is what it currently looks like
As you can see, it's not aligning correctly. Here is the code I tried to accomplish this:
public class BoardImage {
ImagePanel test = new ImagePanel();
GridPanel grid = new GridPanel();
public void returnBoardPanel() {
JFrame frame = new JFrame("JPanel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel image = new JLabel();
image = test.createImage();
image.setLayout(new BorderLayout());
frame.setContentPane(image);
frame.add(grid.paintMe());
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
public static void main (String[] agrs) {
BoardImage test = new BoardImage();
test.returnBoardPanel();
}
}
class ImagePanel extends JPanel{
public JLabel createImage() {
JLabel temp = new JLabel();
ImageIcon icon = new ImageIcon(this.getImage("/boardEdit.jpeg"));
temp.setIcon(icon);
temp.setBounds(0, 0, 552, 575); //needed in order for 24x25 to work
return temp;
}
public Image getImage(String filePath) {
int width, height;
Image tempImage = null;
try {
/* Loads the image, and assigns it to the tempImage var */
URL imagePath = BoardImage.class.getResource(filePath);
tempImage = Toolkit.getDefaultToolkit().getImage(imagePath);
}
catch(Exception e){ //if the filePath does not exist, or something else messed up
System.err.println("We were not able to load the requested image form the given filePath: " + "\n" + filePath);
}
return tempImage;
}
}
class GridPanel extends JPanel{
private JLabel[][] grid;
public GridPanel paintMe(){
this.setBounds(0, 0, 552, 575); //needed in order for 24x25 to work
this.fillGrid();
this.setOpaque(false);
return this;
}
public void fillGrid() {
this.setLayout(new GridLayout(24, 25));
grid = new JLabel[24][25];
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 25; j++) {
grid[i][j] = new JLabel();
grid[i][j].setBorder(new LineBorder(Color.BLACK));//keep this until it works
grid[i][j].setOpaque(false);
this.add(grid[i][j]);
}
}
}
}
I've tried everything I've found online, and on SO, but I can't seem to figure it out. Any suggestions?