gpt4 book ai didi

java - 设置 JFrame 的不透明度时使用 float 和 BigDecimal 缺乏精度

转载 作者:行者123 更新时间:2023-11-30 11:16:15 27 4
gpt4 key购买 nike

我希望这个标题有意义;我正在尝试使用 SwingWorker 设置未装饰框架的不透明度来创建淡入效果。

我尝试将框架的不透明度设置为高于 1.0 时出现异常。当我打印出不透明度的每个增量时,结果如下:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001

我尝试使用 BigDecimal,希望以某种方式保持精度,但失败了。这是我的 SwingWorker 的代码:

private JFrame frame; //initialized in constructor of class

private SwingWorker<Void, Void> fadeIn = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
BigDecimal decimal = new BigDecimal(".1");

while(frame.getOpacity() < 1.0f)
try {
System.out.println(frame.getOpacity());
frame.setOpacity(frame.getOpacity() + decimal.floatValue());
Thread.sleep(30);
} catch(InterruptedException e) {
e.printStackTrace();
}
return null;
}

public void done() {
System.out.println("done");
}
};

淡入效果很好,直到我得到这个异常(上面的代码没有捕获;必须手动捕获):

java.lang.IllegalArgumentException: The value of opacity should be in the range [0.0f .. 1.0f].
at java.awt.Window.setOpacity(Window.java:3609)
at java.awt.Frame.setOpacity(Frame.java:962)
at gui.Splash$1.doInBackground(Splash.java:19)
at gui.Splash$1.doInBackground(Splash.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at javax.swing.SwingWorker.run(SwingWorker.java:334)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

有什么办法可以提高精度吗?我知道我可以使用 AlphaComposite 并重写 paint 方法,但我希望我能保持它像现在一样简单。

有什么方法可以获得更高的精度,以确保我不会将不透明度增加到超出允许的范围?

最佳答案

只运行你自己的值,忘记当前的不透明度是多少:

protected Void doInBackground() throws Exception {

for (int i = 1; i <= 10; i++)
try {
frame.setOpacity(i/10.0);
Thread.sleep(30);
} catch(InterruptedException e) {
e.printStackTrace();
}
return null;
}

这样你就可以保证以 1.0 结束。

关于java - 设置 JFrame 的不透明度时使用 float 和 BigDecimal 缺乏精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com