将文本附加到TextArea(JavaFX 8)的问题 [英] Issues appending text to a TextArea (JavaFX 8)

查看:215
本文介绍了将文本附加到TextArea(JavaFX 8)的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器接收字符串,我想在客户端附加到Textarea(想想聊天窗口)。问题是,当我收到字符串时,客户端会冻结。

I am receiving strings from my server that I want to append into a Textarea on the client side (Think chat window). Problem is, when I receive the string, the client freezes.

insertUserNameButton.setOnAction((event) -> {
        userName=userNameField.getText();
        try {
            connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

public Client() {
    userInput.setOnAction((event) -> {

        out.println(userInput.getText());
        userInput.setText("");

    });
}

private void connect() throws IOException {

    String serverAddress = hostName;
    Socket socket = new Socket(serverAddress, portNumber);
    in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);

    while (true) {
            String line = in.readLine();

        if (line.startsWith("SUBMITNAME")) {
            out.println(userName);

        } else if (line.startsWith("MESSAGE")) {
            Platform.runLater(()->serverOutput.appendText(line.substring(8) + "\n"));

        } else if (line.startsWith("QUESTION")) {
            Platform.runLater(()->serverOutput.appendText(line.substring(8) + "\n"));

        } else if (line.startsWith("CORRECTANSWER")) {
            Platform.runLater(()->serverOutput.appendText(line.substring(14) + "\n"));
        }
    }
}

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

我做了一些研究,似乎在每个追加上使用Platform.runLater应该解决问题。它不适合我。

I have done some research and it seems that using Platform.runLater on each append should fix the problem. It doesn't for me.

任何人都知道它可能是由什么引起的?谢谢!

Anyone has an idea of what it can be caused by? Thank you!

推荐答案

您在FX上拨打 connect()应用线程。因为它通过

You are calling connect() on the FX Application Thread. Since it blocks indefinitely via the

while(true) {
    String line = in.readLine();
    // ...
}

构建,阻止外汇交易平台线程并阻止它执行任何常规工作(呈现UI,响应用户事件等)。

construct, you block the FX Application Thread and prevent it from doing any of its usual work (rendering the UI, responding to user events, etc).

您需要在后台线程上运行它。最好使用 Executor 来管理线程:

You need to run this on a background thread. It's best to use a Executor to manage the threads:

private final Executor exec = Executors.newCachedThreadPool(runnable -> {
    Thread t = new Thread(runnable);
    t.setDaemon(true);
    return t ;
});

然后再做

insertUserNameButton.setOnAction((event) -> {
    userName=userNameField.getText();
    exec.execute(() -> {
        try {
            connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
});

这篇关于将文本附加到TextArea(JavaFX 8)的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆