gpt4 book ai didi

java - 图像未显示在 Canvas 上(Java)

转载 作者:行者123 更新时间:2023-12-01 10:00:28 25 4
gpt4 key购买 nike

我正在创建一个游戏,但背景和主角未加载。这是我声明变量的地方:

private BufferedImage background;   
private BufferedImage player;

这是我获取图像的地方:

try {
background = ImageIO.read(this.getClass().getResourceAsStream("/res/Background.jpg"));
player = ImageIO.read(this.getClass().getResourceAsStream("/res/Player.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

这是我的渲染方法:

public void render() {
BufferStrategy bs = this.getBufferStrategy();

if (bs == null) {
createBufferStrategy(3);
return;
}

Graphics g = bs.getDrawGraphics();

g.drawImage(background, 0, 0, this);
g.drawImage(player, 0, 0, this);

g.dispose();
bs.show();
}

这是我的全类同学:

public class Main extends Canvas implements Runnable, KeyListener {

Thread t;
boolean running = false;

private BufferedImage background;

private BufferedImage player;

public Main() {

setFocusable(true);
requestFocus();
addKeyListener(this);

try {
background = ImageIO.read(this.getClass().getResourceAsStream("/res/Background.jpg"));
player = ImageIO.read(this.getClass().getResourceAsStream("/res/Player.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Override
public void run() {

while (running) {
tick();
render();
}

stop();

}

synchronized void start() {

if (running) return;
running = true;

Thread t = new Thread();
t.start();

}

synchronized void stop() {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.exit(0);
}

public void render() {
BufferStrategy bs = this.getBufferStrategy();

if (bs == null) {
createBufferStrategy(3);
return;
}

Graphics g = bs.getDrawGraphics();

g.drawImage(background, 0, 0, this);
g.drawImage(player, 0, 0, this);

g.dispose();
bs.show();
}

public void tick() {

}

@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();

if (code == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

public static void main(String[] args) {
JFrame f = new JFrame("Mission Sahara");
Main m = new Main();

f.add(m);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setUndecorated(true);
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m.start();
}

}

我的代码有什么问题吗?

最佳答案

您正在 start 方法中创建一个“空”Thread...

Thread t = new Thread();
t.start();

这不会做很多事情。

相反,您可能想做一些类似的事情......

synchronized void start() {

if (running) {
return;
}
running = true;

Thread t = new Thread(this);
t.start();

}

因为Main实现了Runnable

关于java - 图像未显示在 Canvas 上(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36854532/

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