简体   繁体   English

通过Timer设置JDialog不透明度

[英]Setting JDialog opacity by Timer

I am using the following code to fade-in a JDialog with a javax.swing.Timer : 我使用以下代码淡化 JDialogjavax.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: Dialog很好地淡化了所需的效果,但最后发生了IllegalArgumentException说:

 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?? 但问题是我不是很远, i = 0.8F所以它怎么可能是一个非法的论点?
Exception occur at line : setOpacity(i); 行发生异常: setOpacity(i);

Any suggestions? 有什么建议? Solutions? 解决方案?

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. 你的问题是你正在处理浮点数而且==与它们不兼容,因为你无法准确地描绘浮点数为0.8,所以你的Timer永远不会停止。

Use >= . 使用>= Or better still, only use int. 或者更好的是,只使用int。

ie,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM