Setting the opacity of a JDialog timer

I use the following code to attenuate a JDialogwith 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();

Dialogfades beautifully with the desired effect, but finally IllegalArgumentExceptionOccurs, saying that:

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

But the problem is that I do not go far beyond i = 0.8F, so how can this be an illegal argument?
The exception occurs on the line:setOpacity(i);

Any suggestions? Solutions?

+5
source share
1 answer

Your problem is that you are dealing with floating point numbers and ==not working with them, since you cannot accurately display 0.8 in floating point, and therefore your timer will never stop.

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

.,

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();
+8

All Articles