【问题标题】:drawImage is not drawingdrawImage 不绘图
【发布时间】:2012-12-18 11:28:42
【问题描述】:

所以这基本上就是我的代码的工作方式

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(),但仍然没有。

【问题讨论】:

标签: java user-interface drawimage


【解决方案1】:

您不应该使用 Java 中的 Swing 自己管理绘图。

您必须让EDT 线程通过它自己的线程调用适当的重绘方法。这是通过调用JComponentpaint(Graphics g) 来完成的。现在你不应该重写那个方法,而是paintComponent(Graphics g)

所以你应该把你的draw方法从线程移到合适的draw方法:

public void run() {
  while (running)
    repaint();
}

public void paintComponent(Graphics g) {
  draw(g);
}

请注意,您应该以固定帧速率调用重绘并使用双缓冲以避免闪烁。

一个更简单的解决方案是嵌入一些已经为此类工作准备好的东西,例如Processing 框架,效果很好。

【讨论】:

  • use double buffering to avoid flickering ... Swing 组件在默认情况下是双缓冲的 ... 并不是说​​应该回避这个主题,因为默认机制可能并不总能满足人们的需求 ;) +1 来自我跨度>
猜你喜欢
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
  • 2017-08-14
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2015-11-01
相关资源
最近更新 更多