如何在JavaFX中设置定时器来执行显示功能

How to set Timer in JavaFX to execute a display function

我想在每次聊天时(例如:每 2 秒)更新 JAVAFX 场景中窗格的视图 window。我有一个从数据库调用 observableList 的 Display() 函数,我想每 2 秒调用一次,以便用户可以看到即将到来的其他消息,而不仅仅是他发送的消息(我显然可以调用 Display( ) 每次用户发送消息,但他不会收到对方的消息)。 无论如何搜索,我发现你显然可以用 Timeline 做到这一点,所以我创建了这个函数:

   public void RefreshTimer(){
    Timeline timeline = new Timeline(
    new KeyFrame(Duration.seconds(5), e -> {
            DisplayChat(1);
    })
    );
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();
}

我在初始化函数中调用它,但它使场景太慢,我认为调用它的地方不合适。所以我的问题是,我在哪里调用这个函数?

Timeline 在负责更新 GUI 的应用程序线程上运行其 KeyFrame 的处理程序。如果您在此线程上执行 long-running 操作,GUI 将变得无响应。当您以允许您快速更新 GUI 的方式准备好信息时,在不同的线程上获取数据并使用 Platform.runLater 更新 GUI。

ListView<String> listView = ...

ThreadFactory tFactory = r -> {
    // use daemon threads
    Thread t = new Thread(r);
    t.setDaemon(true);
    return t;
};

// use executor to schedule updates with 2 sec delay in between
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor​(tFactory);
service.scheduleWithFixedDelay(() -> {
    String[] newMessages = getNewMessagesFromDB(); // long running operation here

    // do fast GUI update
    Platform.runLater(() -> listView.getItems().addAll(newMessages));
}, 0, 2, TimeUnit.SECONDS);