java - 在 JavaFX 中使用外部线程在 TextFlow 上添加元素

标签 java user-interface javafx textfield

我的程序向服务器发送一条消息,该消息显示在一个窗口中,并从一个窗口接收一条消息,该窗口也添加在客户端的窗口中。

但是我的程序没有显示从服务器收到的消息,尽管我添加了:

textFlow.getChildren().add(text);accept 线程中。

我应该做什么?

public class NewClient extends Application {

Thread send;
Thread accept;

DatagramPacket pack;
DatagramSocket sock;
private List<String> str;
String name , sname;
int listeningPort;
InetAddress server_ip;

String sender;
ScrollPane sp = new ScrollPane();
TextFlow textFlow = new TextFlow();
TextField userTextField = new TextField();
TextField fTextField = new TextField();

private String message;
private String recip = null;
Button button = new Button("Send");

volatile boolean st = false;
Stage theStage;

public Scene Chat_Box() {

    TextFlow textFlow = new TextFlow();
    textFlow.setPadding(new Insets(10));
    textFlow.setLineSpacing(10);
    TextField textField = new TextField();
    textField.setPrefSize(50, 30);
    Button button = new Button("Send");
    button.setPrefSize(80, 30);
    VBox container = new VBox();
    VBox box = new VBox();
    box.getChildren().addAll(sp, textFlow);
    container.setPadding(new Insets(10));
    container.getChildren().addAll(box, new HBox(textField, button));
    VBox.setVgrow(sp, Priority.ALWAYS);
    VBox.setVgrow(textFlow, Priority.ALWAYS);

    textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));

    textField.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.ENTER) {
            button.fire();
        }
    });
    button.setOnAction(e -> {
        st = true;
        Text text;
        if (textFlow.getChildren().size() == 0) {
            text = new Text(textField.getText());
            message = textField.getText();
            System.out.println(message);
        } else {
            message = textField.getText();
            text = new Text("\n" + textField.getText());
        }
        if (textField.getText().contains(":)")) {
            ImageView imageView = new ImageView(
                    "http://files.softicons.com/download/web-icons/network-and-security-icons-by-artistsvalley/png/32x32/Regular/Friend%20Smiley.png");
            // Remove :) from text
            text.setText(text.getText().replace(":)", " "));
            textFlow.getChildren().addAll(text, imageView);
        } else {
            textFlow.getChildren().add(text);
        }
        textField.clear();
        textField.requestFocus();
    });
    VBox vb = new VBox();
    vb.getChildren().addAll(textFlow);
    sp.setVmax(440);
    sp.setPrefSize(400, 300);
    sp.setContent(vb);
    sp.vvalueProperty().bind((ObservableValue<? extends Number>) vb.heightProperty());
    Scene scene2 = new Scene(container, 400, 300);
    return scene2;
}

public void start(Stage stage) throws IOException {
    this.str = getParameters().getRaw();
    name = str.get(0);
    listeningPort = Integer.parseInt(str.get(1));
    server_ip = InetAddress.getByName(str.get(2));
    theStage = stage;
    Scene scene = Chat_Box();
    stage.setScene(scene);
    stage.show();
    send = new Thread() {

        public void run() {
            DatagramSocket sock = null;
            try {
                sock = new DatagramSocket();
            } catch (SocketException ex) {
                Logger.getLogger(NewClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            while (true) {
                InetAddress host = server_ip;
                try {
                    if (st && ( message != null )) {
                        String in = message;
                        byte[] data = new byte[1024];
                        data = in.getBytes();
                        DatagramPacket sendPack = new DatagramPacket(data, data.length);
                        sendPack.setPort(5050);
                        sendPack.setAddress(host);
                        sock.send(sendPack);
                        st = false;
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }

    };
    send.start();
    accept = new Thread() {

        public void run() {
            try {
                sock = new DatagramSocket(listeningPort);
            } catch (SocketException e) {
                e.printStackTrace();
            }
            while (true) {
                byte[] data = new byte[1024];
                pack = new DatagramPacket(data, data.length);
                try {
                    sock.receive(pack);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String incoming = null;
                try {
                    incoming = new String(data, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Text text = new Text(incoming);
                textFlow.getChildren().add(text);
            }
        }
    };
    accept.start();
}

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

}

最佳答案

您应该使用:

Platform.runLater(()->{

 Text text = new Text(incoming);
 textFlow.getChildren().add(text);

});

不允许从其他线程更改SceneGraph。只有JavaFX主线程可以修改SceneGraph。

因此,调用此方法时,您可以将此Runnable对象发送到QUEUE,并且将从JavaFX主线程调用它来修改SceneGraph .

<小时/>

什么是场景图?

The GUI in JavaFX is constructed as a scene graph. A scene graph is a collection of visual elements,called nodes, arranged in a hierarchical fashion. A scene graph is built using the public JavaFX API.

<小时/>

JavaFX 中如何管理事件?

In JavaFX,event queues are managed by a single, operating system–level thread called JavaFX Application Thread. All user input events are dispatched on the JavaFX Application Thread. JavaFX requires that a live scene graph must be modified only on the JavaFX Application Thread.

<小时/>

我应该在哪里使用 Platform.runLater(()->{....});

Every where you are modifying a live SceneGraph from an External Thread other than JavaFX Main Thread.

额外链接:

How JavaFX application thread works?

Platform.runLater and Task in JavaFX

关于java - 在 JavaFX 中使用外部线程在 TextFlow 上添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822806/

相关文章:

javascript - Postman 测试顺利,但 ajax 出错 "Required request body is missing"

javascript - 替换 iframe 的最佳方法

JavaFX TextField - 只允许输入一个字母

testing - 有没有办法自动对网页进行 'look and feel' 测试?

mysql - 如何在 JFXTable View 中添加按钮编辑和删除以及如何将行编辑到 SQL

java - 在maven元素中我如何指定文件的相对路径

java - 即使启动了新 Activity ,也让应用程序留在后台

java - 如何在 Vector Java 的 Vector 中查找(打印)指定字段

java - Java系统代码断点调试

html - target=_blank 还是不target=_blank,这是个问题!