【问题标题】:Text 'fadeIn' animation文本“淡入”动画
【发布时间】:2015-11-12 10:14:03
【问题描述】:

所以我尝试创建一个在屏幕上淡入(从黑色)字符串的动画,但是当我运行它时,它似乎无法正常工作。我没有收到任何错误,只是黑屏(舞台是黑色的)。

代码如下:

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;
    }
}

【问题讨论】:

    标签: java animation javafx


    【解决方案1】:

    您的代码中有多个问题。让我们一一了解:

    1. fadeIn() 中的 for 循环不正确。

    代码:

    for (int i = 0; i > 10; i += 1)
    

    这个循环永远不会执行,因为条件总是为假。您正在寻找的是:

    for (int i = 0; i < 10; i++)
    

    同样,修复另一个循环。

    1. fadeIn() 内部,将firstLoop 初始化为false,然后在KeyFrame 构造函数内部,尝试检查值是否为true,这导致永远不会在Text 上设置文本.

    2. String 的初始化还有一些其他问题,我们现在可以忽略。

    如果你修复了 1 和 2,你应该有一个正在运行的应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多