Repainting Continuously in Java

后端 未结 4 1713
南旧
南旧 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条回答
  • 2021-01-16 07:43

    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.

    0 讨论(0)
  • 2021-01-16 07:45

    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){
    
    0 讨论(0)
  • 2021-01-16 07:52

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题