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

时间:2015-02-11 18:55:45

标签: java image swing paintcomponent imageicon

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

调用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

1 个答案:

答案 0 :(得分:1)

遵循安德鲁汤普森的建议;我用了ImageIO。由于ImageIO抛出错误,我能够弄清楚我访问图像文件的方式是错误的。