drawImage 未绘制 [英] drawImage is not drawing
问题描述
所以这基本上就是我的代码的工作方式
so this is basically how my code is working
class Main extends JFrame implements Runnable {
public Main() {
//init everything
}
public void start() {
running = true;
Thread thread = new Thread(this);
thread.start();
}
public void run() {
while(running) {
render();
}
}
public void render() {
Image dbImage = createImage(width, height);
Graphics dbg = dbImage.getGraphics();
draw(dbg);
Graphics g = getGraphics();
g.drawImage(dbImage, 0, 0, this);
g.dispose();
}
public void draw(Graphics g) {
for(int y=0; y < map.length; y++) {
for(int x=0; x < map.length; x++) {
g.drawImage(map.map[x + y* map.MAP_DIM], x*MAP_DIM, y*MAP_DIM, this);
}
}
}
public static void main(String... args) {
Main main = new Main();
main.start();
}
}
但什么也没画,我看到的都是灰色的.有谁知道可能是什么问题?我尝试在 draw() 方法的末尾执行 repaint(),但仍然没有.
but nothing gets drawn, all i see is gray. anyone know what the problem could be? i tried doing repaint() at the end of the draw() method, but still nothing.
推荐答案
您不应该使用 Java 中的 Swing 自己管理绘图.
You are not supposed to manage drawing by yourself with Swing in Java.
您必须让 EDT 线程通过其自己的线程调用适当的重绘方法.这是通过调用JComponent
的paint(Graphics g)
来完成的.现在你不应该重写那个方法,而是 paintComponent(Graphics g)
代替.
You must let the EDT thread call the appropriate repaint methods by its own thread. This is done by invoking JComponent
's paint(Graphics g)
. Now you shouldn't override that method but paintComponent(Graphics g)
instead.
所以你应该将你的 draw 方法从线程移动到适当的 draw 方法:
So you should move your draw method from the thread to the appropriate draw method:
public void run() {
while (running)
repaint();
}
public void paintComponent(Graphics g) {
draw(g);
}
请注意,您应该以固定的帧速率调用重绘并使用双缓冲以避免闪烁.
Mind that you should call the repaint at a fixed frame rate and use double buffering to avoid flickering.
更简单的解决方案是嵌入已经为此类工作准备的内容,例如 Processing 框架,它可以工作很好.
An even simpler solution would be to embed something already prepared for this kind of work, like a Processing frame, which works very well.
这篇关于drawImage 未绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!