gpt4 book ai didi

java - 图像未出现在小程序中

转载 作者:行者123 更新时间:2023-11-30 03:24:25 25 4
gpt4 key购买 nike

我正在开发一个游戏。我想向小程序添加图像,但直到我调整小程序大小或最小化小程序时它们才会出现。我不知道我的图像观察器是否错误。图像位于正确的路径中。它们位于构建和类文件夹中,拼写正确。我的代码有什么问题吗?任何帮助将不胜感激。

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) {
}

最佳答案

小程序异步加载图像,因此在小程序开始绘制之前图像可能尚未完全加载。但每个值得一提的 Java 组件都实现了一个 ImageObserver,这意味着它将在图像加载时获取更新。因此,要解决该问题,请更改以下内容:

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

此:

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

更新

我错误地认为drawImage方法是JApplet(它是一个ImageObserver)的一部分。您可以简单地将方法声明和绘制行更改为:

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

然后调用它,更改:

sd.draw(g);

致:

sd.draw(g, this);

关于java - 图像未出现在小程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com