JavaFX typewriter effect for label

倖福魔咒の 提交于 2019-12-24 07:17:11

问题


i have some problem with this method. it works fine, but with one little problem. there is too little time among i call this method. so only the last String is printed on a label. but i want that the next String starting printed, only after previous String is finished. Sorry for my English((

 public void some(final String s) {

    final Animation animation = new Transition() {
        {
            setCycleDuration(Duration.millis(2000));
        }

        protected void interpolate(double frac) {


            final int length = s.length();
            final int n = Math.round(length * (float) frac);
            javafx.application.Platform.runLater(new Runnable() {
                @Override
                public void run() {

                    status.setValue(s.substring(0, n));

                }
            }
            );
        }

    };

    animation.play();

}

回答1:


Use the following code to get a typewriting effect.

public void AnimateText(Label lbl, String descImp) {
    String content = descImp;
    final Animation animation = new Transition() {
        {
            setCycleDuration(Duration.millis(2000));
        }

        protected void interpolate(double frac) {
            final int length = content.length();
            final int n = Math.round(length * (float) frac);
            lbl.setText(content.substring(0, n));
        }
    };
    animation.play();

}



回答2:


I don't know if it is an effect that you are trying to achieve, but I have created (ugly) demo how you can do this with TimeLine

public class Main extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    IntegerProperty letters= new SimpleIntegerProperty(0);
    Label label = new Label();
    Button animate = new Button("animate");
    letters.addListener((a, b, c) -> {
        label.setText("animate".substring(0, c.intValue()));
    });

    animate.setOnAction((e)->{
        Timeline timeline = new Timeline();
        KeyValue kv = new KeyValue(letters, "animate".length());
        KeyFrame kf = new KeyFrame(Duration.seconds(3), kv);
        timeline.getKeyFrames().add(kf);
        timeline.play();
    });
    BorderPane pane = new BorderPane(label, null, null, animate, null);

    primaryStage.setScene(new Scene(pane, 300,300));
    primaryStage.show();
}
}


来源:https://stackoverflow.com/questions/27177137/javafx-typewriter-effect-for-label

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