drawImage is not drawing

做~自己de王妃 提交于 2019-12-10 12:14:37

问题


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();
   }
}

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.


回答1:


You are not supposed to manage drawing by yourself with Swing in Java.

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.

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.

An even simpler solution would be to embed something already prepared for this kind of work, like a Processing frame, which works very well.



来源:https://stackoverflow.com/questions/14150140/drawimage-is-not-drawing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!