我试图在可滚动的JPanel
上使用十六进制图像(720x835 GIF)制作六角板。我已经覆盖了paintComponent
方法在不同的特定位置绘制切片,并使用计时器在每个刻度处调用重绘。为什么我的图像不能在JPanel上画图?
当repaint()
被调用时,doDrawing
被调用。当调用doDrawing
时,调用choseTile
来绘制drawImage
的图块。
出于某种原因,瓷砖没有被绘制,我留下了一个空的黑色面板。为什么我的图像不被绘制?是否因为图像太大?面板太大?
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
。
如果打印(X,Y)点(在帧图像的左上角),您正在生成,他们开始在(360,1044)和结束(10800,13574),似乎值太大一个窗口。你确定你是以正确的方式计算它们吗? – rafalopez79 2015-02-11 20:57:41
把g.drawImage(...)放到paintComponent(Graphics g)中怎么办? – crAlexander 2015-02-11 21:22:45
1)应用程序资源在部署时将成为嵌入式资源,所以现在开始访问它们是明智的做法。 [tag:embedded-resource]必须通过URL而不是文件访问。请参阅[信息。页面为嵌入式资源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 2)使用'ImageIO'加载它,它提供了很好的反馈。 – 2015-02-11 21:37:26