gpt4 book ai didi

JavaFX:在 TextArea 中显示文本,每行之间有延迟

转载 作者:行者123 更新时间:2023-12-02 02:13:07 25 4
gpt4 key购买 nike

我正在尝试在 TextArea 中显示文本,每个句子之间有延迟,就像您正在进行对话一样。我尝试使用 sleep 功能,但这不起作用,因为只有当所有方法停止运行时才会显示文本。执行此操作的有效方法是什么:

(伪代码)

textArea.appendText("Goodday sir, how are you doing?");
(0.5 second delay);
textArea.appendText("I'm fine thanks");
(1 second delay);
textArea.appendText("What can I do for you?");
getPlayerInput();
textArea.appendText("Sure, I'll take care of it.");

为了澄清我想要做什么:在 textArea 中显示文本,中间有延迟,并能够在中间运行函数。

最佳答案

作为其他答案中时间线的变体,您可以为要显示的每条消息创建不同的 KeyFrame。这避免了出现“嵌套时间线”的情况,我认为如果您有两到三条以上的消息要逐一显示,这种情况将变得难以管理。

这是使用这个想法的 SSCCE:

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Conversation extends Application {

private TextArea console ;
private TextField input ;
private BooleanProperty readyForInput ;

private Timeline createTimeline(String[] messages) {
Timeline timeline = new Timeline();
Duration delayBetweenMessages = Duration.seconds(1);
Duration frame = delayBetweenMessages ;
for (String msg : messages) {
timeline.getKeyFrames().add(new KeyFrame(frame, e -> console.appendText(msg+"\n")));
frame = frame.add(delayBetweenMessages);
}
timeline.statusProperty().addListener((obs, oldStatus, newStatus) -> {
readyForInput.set(newStatus != Animation.Status.RUNNING);
if (newStatus != Animation.Status.RUNNING) {
input.requestFocus();
}
});
return timeline ;
}

@Override
public void start(Stage primaryStage) {

readyForInput = new SimpleBooleanProperty(false);

console = new TextArea();
console.setEditable(false);

input = new TextField();
input.disableProperty().bind(readyForInput.not());

input.setOnAction(e -> {
String inputText = input.getText();
console.appendText("> "+inputText+"\n");
input.clear();
createTimeline(getMessages(inputText)).play();
});

BorderPane root = new BorderPane(console, input, null, null, null) ;
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();

createTimeline(getMessages(null)).play();
}

private String[] getMessages(String input) {
if (input == null || input.isEmpty()) {
return new String[] {
"Goodday sir, how are you doing?",
"I'm fine thanks",
"What can I do for you?"
};
} else {
// AI logic here...
return new String[] { "Sure, I'll take care of it." };
}
}

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

关于JavaFX:在 TextArea 中显示文本,每行之间有延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49672358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com