Setting JDialog opacity by Timer

浪尽此生 提交于 2019-12-10 15:45:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/10290878/setting-jdialog-opacity-by-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!