2

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

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

在此先感谢您的帮助:)

代码:

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

4

1 回答 1

0

paintComponent 中的@FailX,imageobserver 对象为空。将图像观察者设置为“this”并且它可以工作。

@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
}
于 2012-11-29T11:29:54.453 回答