gpt4 book ai didi

java - 如何实时更新 TextArea 的输入?

转载 作者:行者123 更新时间:2023-12-04 10:50:36 25 4
gpt4 key购买 nike

我目前正在使用 SceneBuilder 开发 JavaFX 程序,该程序也使用 Windows 的命令行。为了向用户展示程序正在做某事,我希望它把控制台输出放到一个文本区域中。到目前为止,它只在一切完成后才更新,而不是实时更新,这是我的目标。

这是我到目前为止的代码,它输入“tree”作为测试。 “textareaOutput”是显示输出的文本区域:

try {
Process p = Runtime.getRuntime().exec("cmd /C tree");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
textareaOutput.appendText(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}

我知道 Swing 中的 MessageConsole,但我不知道 JafaFX 中是否存在类似的东西

最佳答案

这是一个简单的应用程序,它具有与文本区域进行实时命令行绑定(bind)的功能。

  • input 上输入命令(树、时间等)TextField 并按 Enter 键
  • 结果将附加到 text-area不断

  • 演示
    public class CommandLineTextAreaDemo extends Application {

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

    @Override
    public void start(Stage primaryStage) {
    BorderPane root = new BorderPane();
    root.setCenter(getContent());
    primaryStage.setScene(new Scene(root, 200, 200));
    primaryStage.show();
    }

    private BorderPane getContent() {
    TextArea textArea = new TextArea();
    TextField input = new TextField();

    input.setOnAction(event -> executeTask(textArea, input.getText()));

    BorderPane content = new BorderPane();
    content.setTop(input);
    content.setCenter(textArea);
    return content;
    }

    private void executeTask(TextArea textArea, String command) {
    Task<String> commandLineTask = new Task<String>() {
    @Override
    protected String call() throws Exception {
    StringBuilder commandResult = new StringBuilder();
    try {
    Process p = Runtime.getRuntime().exec(command);
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    commandResult.append(line + "\n");
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    return commandResult.toString();
    }
    };

    commandLineTask.setOnSucceeded(event -> textArea.appendText(commandLineTask.getValue()));

    new Thread(commandLineTask).start();
    }
    }

    如果你想使用 TextArea独立(不使用 input TextField),你可以做这样的事情。
    textArea.setOnKeyReleased(event -> {
    if(event.getCode() == KeyCode.ENTER) {
    String[] lines = textArea.getText().split("\n");
    executeTask(textArea, lines[lines.length - 1]);
    }
    });

    关于java - 如何实时更新 TextArea 的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491390/

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