在JavaFX中,Platform.runLater太慢了 [英] Platform.runLater too slow in JavaFX

查看:1878
本文介绍了在JavaFX中,Platform.runLater太慢了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的JavaFx应用程序中执行一个线程,我还需要更新我的listview,这就是为什么我在其中使用了Platform.runLater。问题是它似乎太慢了,因为它会在其中跳转if状态。 listView.setItems(model.getEmailList()); 部分执行没有问题,但忽略条件即使我打印两个值我想比较它们是不同的。我怎样才能改进它?因为我不能在平台外移动那个 if ,因为我试图在我的JavaFX应用程序的一个线程中显示它。

I'm trying to execute a thread inside my JavaFx application and I also need to update my listview, reason why I used a Platform.runLater inside it. The problem is that it seems to be too slow, since it jumps the if state inside it. The listView.setItems(model.getEmailList()); part is executed without problem, but ignore the the condition even if when I print the two value I wanna compare they are different. How can I improve it? Because I cannot move that if outside the Platform since I'm trying to display it in a thread of my JavaFX application.

new Thread() {
        @Override
        public void run() {
            while (true) {
                try {
                    int currentOnServer = model.askNumbOfEmail();
                    if (emailForClient != currentOnServer) {
                        model.reLoadData();
                        Platform.runLater(() -> {
                            listView.setItems(model.getEmailList());
                            if (currentOnServer > emailForClient) {
                                new Alert(Alert.AlertType.INFORMATION, "Hai recevuto un email!").showAndWait();
                            }
                        });
                        emailForClient = currentOnServer;
                    }
                } catch (IOException ex) {
                    Thread.currentThread().interrupt();
                    return;
                } catch (ParseException ex) {
                    System.out.println("ParseException ERROR!");
                }
            }
        }
    }.start();


推荐答案

你的if语句不起作用,因为你是在单独的线程中更改条件的一部分:

Your if statement doesn't work because you're changing part of the condition in a separate thread:

emailForClient = currentOnServer

当您使用线程时,这是一个常见问题。您需要修改代码的逻辑以便于并行执行。您可以创建一个临时变量来存储 emailForClient 并在 Platform.runLater 中使用它:

This is a common problem when you're working with threads. You need to modify the logic of your code to facilitate parallel execution. You can create a temp variable to store emailForClient and use it inside Platform.runLater instead:

model.reLoadData();
final int currentEmail = emailForClient; // I'm assuming emailForClient is an int

Platform.runLater(() -> {
    listView.setItems(model.getEmailList());

    if (currentOnServer > currentEmail) {
        new Alert(Alert.AlertType.INFORMATION, "Hai recevuto un email!").showAndWait();
    }
});

emailForClient = currentOnServer;

这篇关于在JavaFX中,Platform.runLater太慢了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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