Repainting Continuously in Java

2019-02-20 15:43发布

问题:

I have a Java program that uses threads. In my run method, I have:

public void run() {
    while(thread != null){
        repaint();
        System.out.println("hi");
        try {  
            Thread.sleep(1000);  
        } catch (InterruptedException e) {  
            break;  
        }  
    }
}

public void paintComponent(Graphics g) {
    // painting stuff
}

The problem is that the run method is executed, but the paintComponent section is not called. If this is not the right way to keep repainting the component, then how should I repaint it?

回答1:

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){


回答2:

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



回答3:

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.



回答4:

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.