通过计时器设置JDialog不透明度

通过计时器设置JDialog不透明度

本文介绍了通过计时器设置JDialog不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将JDialogjavax.swing.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();

Dialog很好地淡入了期望的效果,但是最后出现了IllegalArgumentException,说:

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]

但是问题是我来不及i = 0.8F,所以怎么可能是非法论点呢?
在第setOpacity(i);

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?

推荐答案

您的问题是您正在处理浮点数,而==不能很好地与它们配合使用,因为您无法准确地在浮点数中描绘0.8,这样您的计时器将永远不会停止.

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.

使用>=.或更妙的是,仅使用int.

Use >=. Or better still, only use 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();

这篇关于通过计时器设置JDialog不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:57