简体   繁体   English

是否在JavaFx…线程中将项目添加到ListView?

[英]Adding items to ListView in JavaFx… threading?

I'm trying to add a string to ListView in JavaFX whilst processing, but it keeps freezing my GUI. 我正在尝试在处理时向JavaFX中的ListView添加一个字符串,但它一直冻结我的GUI。

I've tried the following threading - but can't seem to get it to work for a ListView. 我尝试了以下线程-但似乎无法使其用于ListView。
Does anybody know how/have an example of how I can update a ListView in JavaFX whilst processing data? 有人知道如何/拥有如何在处理数据时在JavaFX中更新ListView的示例吗?

new Thread(new Runnable() {
    @Override public void run() {
        for (int i=1; i<=1000000; i++) {
            final int counter = i;
            Platform.runLater(new Runnable() {
                @Override public void run() {
                    recentList.getItems().add(Integer.toString(counter));
                }
            });
        }
    }}).start();

Using Platform.runLater() is the correct way to go. 使用Platform.runLater()是正确的方法。 You could, also, store the String result from Integer.toString(counter) in the background thread (not the UI one). 您也可以将Integer.toString(counter)的String结果存储在后台线程(而不是UI线程)中。 By the way, you should use String.valueOf (there is a thread on StackOverflow which talks about it). 顺便说一句,您应该使用String.valueOf(StackOverflow上有一个谈论它的线程)。

I assume your UI is freezing because of the execution speed of the (very simple) loop. 由于(非常简单)循环的执行速度,我认为您的UI处于冻结状态。

You should also have a look at Concurrency in JavaFX 您还应该看看JavaFX中的并发性

Your GUI hangs because you are blocking the JavaFX application thread by calling Platform.runLater() continuously in your Thread. GUI挂起是因为您通过在线程中连续调用Platform.runLater()来阻止JavaFX应用程序线程。

You can perform a quick fix by adding a sleep statement inside your for-loop to avoid it. 您可以通过在for循环中添加sleep语句来避免此quick fix ,从而执行quick fix

for (int i=1; i<=1000000; i++) {
     final int counter = i;
     Platform.runLater(new Runnable() {
        @Override public void run() {
            recentList.getItems().add(Integer.toString(counter));
        }
     });
     // Add Sleep Time
     Thread.sleep(some milli seconds);
}

To use a more proper and advisable way, use an AnimationTimer , as shown in 要使用更合适和明智的方法,请使用AnimationTimer ,如下所示:

JavaFX - Concurrency and updating label JavaFX-并发和更新标签

You can do the animation / ui update after adding those strings in the list or use Platform.runLater only once (not advisable): 您可以在列表中添加这些字符串后进行动画/ ui更新,或者仅使用一次(不建议使用)Platform.runLater:

Platform.runLater(new Runnable() {
  for (int i=1; i<=1000000; i++) {
        final int counter = i;

            @Override public void run() {
                recentList.getItems().add(Integer.toString(counter));
            }
     }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM