tags:

views:

41

answers:

1

Hi: i have jLabel and i want to change its opacity (alpha value) each one second , i tried something like that but its not change each one second , jlable change its opacity only with last alpha value .

  Color color = jLabel1.getBackground();
    int alpha = 255;
    long initTime = System.currentTimeMillis();
    while(true){
        if(System.currentTimeMillis() - initTime >= 1000){
        initTime = System.currentTimeMillis();
        alpha -=1;
        Color color2 = new Color(color.getRed(),color.getGreen(),color.getBlue(),alpha);
        jLabel1.setBackground(color2);

        }
        if(alpha<=0)
            break;
    }
+1  A: 

If you're running this on the Event Dispatch Thread, using say SwingUtilities.invokeLater then the repaint will only happen after your code has finished executing. For repeated updates, use the Swing Timer, as detailed in this sun tutorial:

You might also look into the Trident animation library for Swing.

mdma
+1 Here's a related example that uses `javax.swing.Timer` to ensure EDT execution: http://stackoverflow.com/questions/2228735/how-do-i-fade-an-image-in-swing/2234020#2234020
trashgod