我正在用Java制作棋盘游戏,我正试图在JPanel中渲染棋盘。我试图这样做的方法是插入一个板的图像(由JLabel表示)和一个网格(也由JPanel表示)。这个想法是每个网格方块对应于电路板图像上的方块。
这是目前的样子
正如您所看到的,它没有正确对齐。这是我试图完成的代码:
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]);
}
}
}
}
我已经尝试过我在网上找到的所有东西,并且在SO上,但我似乎无法弄明白。有什么建议?