views:

60

answers:

3

Hi all:

Say if I have a Java Graphics object, and I want to draw a line or a rectangle on it. When I issue the command to draw, it appears on screen immediately. I just wonder how could I make this progress as a fade-in / fade-out effect, same as what you can achieve in Javascript.

Any thoughts?

Many thanks for the help and suggestions in advance!

+2  A: 

Take a look at the Java Timing Framework.

Faisal Feroz
+2  A: 

Have a look at the AlphaComposite class for the transparency, and the Swing based Timer class for timing.

The Java 2D API Sample Programs has demos. under the Composite heading that show how to tie them together.

Andrew Thompson
+2  A: 

You could try painting the image over and over again but with a different opacity (alpha) value. Start from 0 (completely transparent) and gradually increase to 1 (opaque) in order to produce a fade-in effect. Here is some test code which might help:

float alpha = 0.0f;

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    //set the opacity
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, alpha));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    //do the drawing here
    g2d.drawLine(10, 10, 110, 110);
    g2d.drawRect(10, 10, 100, 100);

    //increase the opacity and repaint
    alpha += 0.05f;
    if (alpha >= 1.0f) {
        alpha = 1.0f;
    } else {
        repaint();
    }

    //sleep for a bit
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
}
dogbane