Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting JDialog opacity by Timer

I am using the following code to fade-in a JDialog with a javax.swing.Timer:

    float i = 0.0F;
    final Timer timer = new Timer(50, null);
    timer.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (i == 0.8F){
                timer.stop();
            }
            i = i + 0.1F;
            setOpacity(i);
        }
    });
    timer.start();

The Dialog is nicely faded-in with the desired effect but at last, an IllegalArgumentException Occurs saying that:

 The value of opacity should be in the range [0.0f .. 1.0f]

But the problem is I am not going far fro i = 0.8F so how can it be a illegal argument??
Exception occur at line : setOpacity(i);

Any suggestions? Solutions?

like image 885
Asif Avatar asked Apr 24 '12 02:04

Asif


1 Answers

Your problem is that you're dealing with floating point numbers and == doesn't work well with them since you cannot accurately depict 0.8 in floating point, and so your Timer will never stop.

Use >=. Or better still, only use int.

i.e.,

int timerDelay = 50; // msec
new Timer(timerDelay, new ActionListener() {
    private int counter = 0;

    @Override
    public void actionPerformed(ActionEvent e) {
        counter++;
        if (counter == 10){
            ((Timer)e.getSource()).stop();
        }
        setOpacity(counter * 0.1F);
    }
}).start();
like image 76
Hovercraft Full Of Eels Avatar answered Oct 16 '22 02:10

Hovercraft Full Of Eels