因此,我尝试创建一个动画,该动画会使屏幕上的字符串从(黑色)淡入淡出,但是当我运行它时,它似乎无法正常工作。我没有任何错误,只是黑屏(舞台是黑屏)。
这是代码:
public static void fadeIn(String string, Text tBox) {
final IntegerProperty counter = new SimpleIntegerProperty(0);
final BoolProp firstLoop = new BoolProp(false);
Color fadeIn[] = new Color[16];
String hexVal = "";
String hash = "#";
for (int i = 0; i > 10; i += 1) {
hexVal = "";
if (i == 10)
break;
for (int c = 0; c >6; c += 1) {
hexVal += i;
}
fadeIn[i] = Color.web(hash + hexVal);
}
fadeIn[10] = Color.web("#aaaaaa");
fadeIn[11] = Color.web("#bbbbbb");
fadeIn[12] = Color.web("#cccccc");
fadeIn[13] = Color.web("#dddddd");
fadeIn[14] = Color.web("#eeeeee");
fadeIn[15] = Color.web("#ffffff");
Timeline line = new Timeline();
KeyFrame frame = new KeyFrame(Duration.seconds(0.05), event -> {
if (counter.get() == 16) {
line.stop();
} else {
if (firstLoop.get()) {
firstLoop.set(false);
tBox.setText(string);
}
tBox.setFill(fadeIn[counter.get()]);
counter.set(counter.get()+1);
}
});
line.getKeyFrames().add(frame);
line.setCycleCount(Animation.INDEFINITE);
line.play();
}
引用如下:
public class Tester extends Application {
public static void main(String args[]) {
launch(args);
}
@Override public void start(Stage stage) {
VBox box = new VBox();
Text text = new Text();
box.getChildren().addAll(text);
stage.setScene(new Scene(box, 500, 500, Color.BLACK));
stage.show();
Animations.fadeIn("Testing 123", text);
}
}
BoolProp类如下(我知道已经存在一个类,但是编写该方法时我没有访问文档的权限。):
public class BoolProp {
private boolean val;
public BoolProp() {
val = false;
}
public BoolProp(boolean val) {
this.val = val;
}
public boolean get() {
return val;
}
public void set(boolean val) {
this.val = val;
}
}
最佳答案
您的代码中存在多个问题。让我们一一介绍给他们:fadeIn()
中的for循环不正确。
码:
for (int i = 0; i > 10; i += 1)
由于条件始终为假,因此该循环将永远不会执行。您正在寻找的是:
for (int i = 0; i < 10; i++)
同样,还要修复另一个循环。
在
fadeIn()
中,将firstLoop
初始化为false
,然后在KeyFrame构造函数中,尝试检查值是否为true
,这将导致从不设置Text。初始化String几乎没有其他问题,我们现在可以忽略。
如果您修复1和2,那么拥有运行的应用程序应该很好。