图片不会出现在applet中

时间:2015-06-03 04:07:40

标签: java swing applet paint keylistener

我正在开发一个游戏。我想将图像添加到applet中,但是在我调整大小或最小化applet之前它们不会出现在那里。我不知道我的图像观察者是否错误。 图像在正确的路径中。它们在构建和类文件夹中具有正确的拼写。我的代码出了什么问题? 任何帮助将不胜感激。

public class game extends JApplet implements KeyListener, Runnable {

ScreenDir sd;
Image ball;
Image flower;

public void init() {

    sd = new ScreenDir(this);
    ball = getImage(getCodeBase(), "ball.jpg");
    ballb = new Ball(50, 50, 30, 40, Color.red, ball, sd);
    sd.add(ball);
    flower = getImage(getCodeBase(), "flower.gif");
     //class Flower is just defined like class Ball
    flowerf = new Flower(60, 100, 30, 30, Color.green, flower, sd);
    sd.add(flower);

}

public void paint(Graphics g) {
    sd.draw(g);

}

//These are for moving the ball

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
}

@Override
public void keyReleased(KeyEvent e) {
}

@Override
public void run() {
    while (true) {
        repaint();
        try {
            Thread.sleep(15);
        } catch (InterruptedException ex) {}}}



  public class ScreenDir {

ArrayList<Object> olist;
JApplet parent;

public ScreenDir(JApplet parent) {
    this.parent = parent;
    olist = new ArrayList<>();
}

public void add(Object o) {
    olist.add(o);
}

Image Img;
Graphics oG;

Img  = parent.createImage(parent.getWidth(), parent.getHeight());
oG  = offImg.getGraphics();

for(int i = 0;i<olist.size ();i++){
         olist.get(i).draw(offG);
}

g.drawImage (Img,0, 0, parent);
 }


    public class Ball extends Object {

ScreenDir sd;

public ball(int x, int y, int w, int h, Color c, Image pi, ScreenDir sd) {
    {
        this.sd = sd;
    }
public void draw(Graphics g) {
    g.drawImage(pi, x, y, w, h, null);
}


public abstract class Object {

    int x, y, w, h;
    Color c;
    Image pi;

    public Object(int x, int y, int w, int h, Color c, Image pi) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.c = c;
        this.pi = pi;
    }

    public abstract void draw(Graphics g) {
    }

1 个答案:

答案 0 :(得分:2)

Applet异步加载图像,因此在applet进行绘制之前,图像可能没有完全加载。但是值得一提的每个Java组件都实现了ImageObserver,这意味着它将获得图像加载的更新。所以要解决这个问题,请更改:

g.drawImage(pi, x, y, w, h, null);

this:

g.drawImage(pi, x, y, w, h, this);

更新

我错误地认为drawImage方法是JAppletImageObserver)的一部分。您可以简单地更改方法声明&amp;画线:

public void draw(Graphics g, ImageObserver io) {
    g.drawImage(pi, x, y, w, h, io);
}

然后调用它,改变:

sd.draw(g);

致:

sd.draw(g, this);