views:

315

answers:

4

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);
    frame.setVisible(true);

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

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

Jorn
+1  A: 

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.

Paul Whelan
JPanel is lightweight. Heavyweight components are those with peers (AWT Canvas, Panel, Window, Frame, Dialog, TextField, TextArea, List, Checkbox, etc.).
Tom Hawtin - tackline
Thanks for the clarification I am going to edit the answer hope thats ok
Paul Whelan
+5  A: 

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.

camickr
Using a Timer is really the only way to go. If you try to schedule painting inside PaintComponent(), you run the risk of the component not repainting immediately if it is un-hidden when other components or programs are moved over it in a windowing environment.
clartaq
+1  A: 

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

Rastislav Komara