无法在JPanel上绘制.jpeg

时间:2012-11-14 18:55:01

标签: image jpanel draw

我正在制作一个游戏,当我移动它时,我需要画一个棋盘和棋子。我现在已经搜索了几个小时,但我找不到解决方案。

它们与班级位于同一文件夹中。

提前感谢您的任何帮助:)

代码:

import java.awt.*;
import javax.swing.*;

public class MyPanel extends JPanel{
    private static final long serialVersionUID = 1L;

    public void paint(Graphics g) {
        try {   
            Image board = new ImageIcon("images/ChackerBoard.jpeg").getImage();
            Image black = new ImageIcon("images\\BlackPawn.jpeg").getImage();
            Image white = new ImageIcon("images\\WhitePawn.jpeg").getImage();

            this.setSize(320, 320);

            g.drawImage(board, 0, 0, this);
            for (int i = 0; i < Game.BlackList.size(); i++) {
                g.drawImage(black, (Game.BlackList.get(i).GetX() * 40) - 36, (Game.BlackList.get(i).GetY() * 40) - 36, this);
            }
            for (int i = 0; i < Game.WhiteList.size(); i++) {
                g.drawImage(white, (Game.WhiteList.get(i).GetX() * 40) - 36, (Game.WhiteList.get(i).GetY() * 40) - 36, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

图片:

http://i.stack.imgur.com/bhuc2.jpg

http://imageshack.us/a/img7/8673/checkerboardo.jpg

1 个答案:

答案 0 :(得分:0)

paintComponent中的@FailX,imageobserver对象为null。将图像观察者设置为&#34;这个&#34;它有效。

@Override
protected void paintComponent( Graphics g ){
    super.paintComponent( g );
    g.drawImage(img, 0, 0, this); //Image is also drawn
    g.drawLine( 10, 10, 100, 50 ); //Line is drawn
    g.draw3DRect(20,20,50,30,true); // Rectangle is drawn
}