问题
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