Repainting Continuously in Java

后端 未结 4 1764
南旧
南旧 2021-01-16 07:09

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

public void run() {
    while(thread != null){
        repaint();
        System.out.print         


        
4条回答
  •  猫巷女王i
    2021-01-16 07:59

    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.

提交回复
热议问题