在JavaFX中使用sleeps的Settext

在JavaFX中使用sleeps的Settext,java,javafx,character,sleep,settext,Java,Javafx,Character,Sleep,Settext,我想通过逐字符写入标签上的数据来设置标签的文本 到目前为止,代码是 public void texting(String inc) { String a = ""; try { for (char c : inc.toCharArray()) { a = a + String.valueOf(c); labelHeader.setText(a); System.out.println(a);

我想通过逐字符写入标签上的数据来设置标签的文本

到目前为止,代码是

public void texting(String inc) {
    String a = "";
    try {
        for (char c : inc.toCharArray()) {
            a = a + String.valueOf(c);
            labelHeader.setText(a);
            System.out.println(a);
            Thread.sleep(300);
        }
    } catch (InterruptedException e) {
    }

}
控制台显示的文本与我期望的完全一样(逐字符),但是标签等待过程结束,然后在字符之间没有延迟地显示数据


原因可能是什么,我如何修复此问题?

您正在使用
Thread.sleep()
阻止FX应用程序线程。这是管理所有ui更新的线程,包括呈现ui和处理用户输入。由于您正在阻止此线程,因此会阻止它执行其正常工作

相反,您需要在后台线程中执行“wait”操作,或者使用某种计时器来管理它。最简单的方法可能是使用来实现计时器

所以你可以做:

public void texting(String inc) {    
    IntegerProperty textLength = new IntegerProperty();
    Timeline timeline = new Timeline(new KeyFrame(Duration.millis(300)), e -> {
        textLength.set(textLength.get()+1);
        labelHeader.setText(inc.substring(0, textLength.get()));
    });
    timeline.setCycleCount(inc.length());
    timeline.play();

}
一个微小的变化是创建一个执行一次的时间线,并操纵您提取的子字符串的长度:

public void texting(String inc) {    
    IntegerProperty textLength = new IntegerProperty();
    Timeline timeline = new Timeline(new KeyFrame(Duration.millis(300 * inc.length())), 
        new KeyValue(textLength, inc.length()));
    labelHeader.textProperty().bind(Bindings.createStringBinding(() ->
        inc.substring(0, textLength.get()), textLength));
    timeline.play();

}
如果要使用线程执行此操作,必须执行以下操作:

public void texting(String inc) {
    Thread t = new Thread(() -> {
        try {
            for (int i = 1; i <= inc.length(); i++) {
                String text = inc.substring(0, i);
                Platform.runLater(() -> labelHeader.setText(text));
                Thread.sleep(300);
            }
        } catch (InterruptedException exc) {
            exc.printStackTrace();
        }
    });
    t.setDaemon(true); // thread will not stop application exit
    t.start();
}
公共无效文本(字符串公司){
线程t=新线程(()->{
试一试{
对于(inti=1;i labelHeader.setText(text));
睡眠(300);
}
}捕获(中断异常exc){
exc.printStackTrace();
}
});
t、 setDaemon(true);//线程将不会停止应用程序退出
t、 start();
}

还有各种其他选项…

不要在当前事件线程中使用
sleep
。您需要使用某种类型的任务或计时器(抱歉,在JavaFX中没有太多经验),首先看一下