摇摆:当我使用Toolkit.getDefaultToolkit()。sync();时,动画仍然断断续续

时间:2018-08-31 03:45:07

标签: java swing animation synchronization

我正在尝试使用Thread.sleep()每100毫秒绘制一次图像。但是我听说将Thread.sleep()与swing一起使用时,它的运动像断断续续。所以我添加了代码Toolkit.getDefaultToolkit()。sync(),但它看起来仍然很结巴。

正确地说,它看起来像2〜300ms的延迟,并在短时间内立即绘制。

我的意思是当我想移动图像时,我希望看起来像

绘制-睡眠-绘制-睡眠-...

但是看起来像

绘制-睡眠-睡眠-睡眠-绘制-绘制-绘制-睡眠-...

对不起我的解释,希望您能理解。

这是我的代码。

public abstract class EngineViewer implements Runnable
{
     private int _frameInterval = 100;
     private CameraInterface _camera;

     private Canvas _canvas;

     public EngineViewer(int displayWidth, int displayHeight, int resolutionWidth, int resolutionHeight)
     {
         Thread thread = new Thread(this);
         thread.start();
     }

     private void Sleep()
     {
         try { Thread.sleep(_frameInterval); }
         catch(Exception e) { }
     }


     @Override
     public void run()
     {
         while(true)
         {
             Clear();

             _camera.Draw(_canvas);

             Draw();

             Sleep();
         }
     }

     protected abstract void Draw();
}

将摄像机注册到EngineViewer,EngineViewer每次都调用Camera.Draw()。 相机将图像绘制到要从SwingViewer._buffer获取的缓冲区中。

然后在Draw Method上将_buffer绘制到_panel,然后调用Toolkit.getDefaultToolkit()。sync()。

public class SwingViewer extends EngineViewer
 {       
     private JFrame _frame;

     private SWPanel _panel;

     private BufferedImage _buffer;
     private Graphics2D _graphic;

     public SwingViewer(String name, int displayWidth, int displayHeight, int resolutionWidth, int resolutionHeight)
     {
         super(displayWidth, displayHeight, resolutionWidth, resolutionHeight);

         _frame = new JFrame(name);
         _frame.setSize(displayWidth, displayHeight);
         _frame.setVisible(true);
         _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         _panel = new SWPanel();
         _frame.add(_panel);
     }

     @Override
     public void Draw()
     {
         if(_panel != null)
             _panel.Draw();

         Toolkit.getDefaultToolkit().sync();
     }

     private class SWPanel extends JPanel
     {
         private static final long serialVersionUID = 1;

         private void Draw()
         {
             repaint();
         }

         @Override
         public void paintComponent(Graphics g)
         {
             super.paintComponent(g);

             g.drawImage(_buffer, 0, 0, EngineViewer.DisplayWidth(), EngineViewer.DisplayHeight(), null);
         }
     }
 }

0 个答案:

没有答案