开发者

Why does repaint(long) repaint immediately?

According to the Javadoc, JComponent.repaint(long) is supposed to schedule a repaint() sometime in the future. When I try using it it always triggers an immediate repaint. What am I doing wrong?

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Repaint
{
  public static final boolean works = false;

      private static class CustomComponent extends JPanel
  {
    private float alpha = 0;

    @Override
    protected void paintComponent(Graphics g)
    {
      super.paintComponent(g);
      Graphics2D g2d = (Graphics2D) g;
      g2d.setComposite(
        AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
      g2d.setPaint(Color.BLACK);
      g2d.fillRect(0, 0, getWidth(), getHeight());
      alpha += 0.1;
      if (alpha > 1)
        alpha = 1;
      System.out.println("alpha=" + alpha);
      if (!works)
        repaint(1000);
    }
  }

  public static void main(String[] args)
  {
    final JFrame frame = new JFrame();
    frame.getContentPane().add(new CustomComponent());
    frame.setSize(800, 600);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  开发者_如何学Go  frame.setVisible(true);

    if (works)
    {
      new Timer(1000, new ActionListener()
      {
        @Override
        public void actionPerformed(ActionEvent e)
        {
          frame.repaint();
        }
      }).start();
    }
  }
}


Note that the Javadoc says the method will cause a repaint to happen within (not after) the specified time.


If you want to schedule something to be repainted, then you should be using a Swing Timer. You should not be scheduling painting from withing the paintComponnt(..) method. You can't control when the paintComponent() method is called.


The parameter says tm - maximum time in milliseconds before update it does not say it won't do so immediately also the javadocs say

Repaints the component. If this component is a lightweight component, this results in a call to paint within tm milliseconds.


If you search a little bit you find that this parameter is ignored in derived classes. ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜