gpt4 book ai didi

java - 为什么我的图像没有在 JPanel 上绘制?

转载 作者:行者123 更新时间:2023-12-01 11:55:39 25 4
gpt4 key购买 nike

我正在尝试在可滚动的 JPanel 上制作一个带有十六进制图像 (720x835 GIF) 的六角板。我已重写 paintComponent 方法以在不同的特定位置绘制图 block ,并使用计时器在每个刻度处调用重绘。

当调用repaint()时,doDrawing被调用。当调用doDrawing时,会调用choseTile来使用drawImage绘制图 block 。

由于某种原因,图 block 没有被绘制,我留下了一个空的黑色面板。为什么我的图像没有被绘制?是因为图片太大吗?面板太大?

public class MapPanel extends JPanel {

// Images for the tiles
Image tile1;
Image tile2;
//etc

// measurements for the tiles
int tileX = 720;
int tileY = 835;
int dimensionX = 14760;
int dimensionY = 14613;

//Use this to keep track of which tiles goes where on a 20x20 board
public int[][] hexer;

/**
* Create the panel.
*/
public MapPanel(int[][] hexMap) {

hexer = hexMap;
setPreferredSize(new Dimension(dimensionX, dimensionY));
setBackground(Color.black);
setFocusable(true);
loadImages();

Timer timer = new Timer(140, animatorTask);
timer.start();
}

//getting the images for the tiles
private void loadImages() {
// Setting the images for the tiles
ImageIcon iid1 = new ImageIcon("/Images/tiles/tile1.gif");
tile1 = iid1.getImage();
ImageIcon iid2 = new ImageIcon("/Images/tiles/tile2.gif");
tile2 = iid2.getImage();
//etc
}

// Drawing tiles
private void choseTile(Graphics g, int x, int y, int id) {
switch (id) {
case 1:
g.drawImage(tile1, x, y, this);
break;
case 2:
g.drawImage(tile2, x, y, this);
break;
//etc

}
}

// repainting stuff
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

doDrawing(g);
}

private void doDrawing(Graphics g) {
int actualX;
int actualY;

//set the painting coordinates and image ID then call the method to draw
for (int x = 0; x < 20; x++) {
for (int y = 0; y < 20; y++) {
if ((y + 1) % 2 == 0) {
actualX = x * tileX + 720;
} else {
actualX = x * tileX + 360;
}
if((x + 1) % 2 == 0){
actualY = (y/2) * 1253 + 418;
}else{
actualY = (y+1)/2 * 1253 + 1044;
}
if(hexer[x][y] != 0)
choseTile(g, actualX, actualY, hexer[x][y]);
}
}
}

private ActionListener animatorTask = new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
};
}

编辑:我已经检查过以确保图像不null

最佳答案

遵循安德鲁·汤普森的建议;我用的是ImageIO。由于 ImageIO 抛出的错误,我发现访问图像文件的方式是错误的。

关于java - 为什么我的图像没有在 JPanel 上绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28462246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com