Repainting Continuously in Java

有些话、适合烂在心里 提交于 2019-12-01 13:28:56

Cal repaint from a Swing Timer. That will not block the GUI, and will happen at whatever interval specified in the timer. Of course, by the nature of Swing/AWT painting, if the timer is set to repeat too fast, calls to paint might be coalesced (effectively ignored).

Also, make sure the method is an override using:

@Override
public void paintComponent(Graphics g){

You should only repaint a component when you need to (ie, when you update it).

Depending on what you're doing, you might also be interested in this. This is taken from Killer Game Programming in Java by Andrew Davison. He talks about active rendering. Your game loop is effectively:

public void run()
{
  while (running)
  {
    gameUpdate();                             // game state is updated
    gameRender();                             // render to a buffer
    paintScreen();                            // draw buffer to screen

    try
    {
      Thread.sleep(20);
    }
    catch (InterruptedException e) {;}
  }
}

And, the implementation of paint screen is (defined by a subclass of JComponent):

private void paintScreen()
{
  final Graphics2D g2d;

  try
  {
    g2d = (Graphics2D) this.getGraphics();
    if (g2d != null && (backbuffer != null))
    {
      g2d.drawImage(backbuffer, 0, 0, null);
    }

    Toolkit.getDefaultToolkit().sync();       // sync the display on some systems [1]
    g2d.dispose();
  }
  catch (Exception e)
  {
    ;
  }
}

From the book:

[Note 1] The call to Tookkit.sync() ensures that the display is promptly updated. This is required for Linux, which doesn't automatically flush its display buffer. Without the sync() call, the animation may be only partially updated, creating a "tearing" effect.

You have to call paint(g) for a heavy-weight container such as a JFrame. You call paintComponent(g) for light-weight containers like a JButton. See if that works.

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