从服务线程更新JavaFX GUI

joh*_*co3 3 java multithreading javafx

如何从JavaFX服务中安全地更新JavaFX GUI上的小部件.我记得当我使用Swing进行开发时,我曾经"稍后调用"和其他各种swing工作器实用程序,以确保在Java事件线程中安全地处理对UI的所有更新.以下是处理数据报消息的简单服务线程的示例.缺少的位是解析数据报消息的位置,并更新相应的UI小部件.正如您所看到的,服务类非常简单.

我不确定是否需要使用简单的绑定属性(如消息),或者我应该将小部件传递给我的StatusListenerService的构造函数(这可能不是最好的事情).有人可以给我一个很好的类似例子,我可以从中工作.

public class StatusListenerService extends Service<Void> {
    private final int mPortNum;

    /**
     *
     * @param aPortNum server listen port for inbound status messages
     */
    public StatusListenerService(final int aPortNum) {
        this.mPortNum = aPortNum;
    }

    @Override
    protected Task<Void> createTask() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                updateMessage("Running...");
                try {
                    DatagramSocket serverSocket = new DatagramSocket(mPortNum);
                    // allocate space for received datagrams
                    byte[] bytes = new byte[512];
                    //message.setByteBuffer(ByteBuffer.wrap(bytes), 0);
                    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);                    
                    while (!isCancelled()) {                    
                        serverSocket.receive(packet);
                        SystemStatusMessage message = new SystemStatusMessage();
                        message.setByteBuffer(ByteBuffer.wrap(bytes), 0);                         
                    }
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
                updateMessage("Cancelled");
                return null;
            } 
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*s_D 5

"低级"方法Platform.runLater(Runnable r)用于更新UI.这将r在FX应用程序线程上执行,相当于Swing的SwingUtilities.invokeLater(...).因此,一种方法就是Platform.runLater(...)call()方法内部调用并更新UI.但是,正如您所指出的,这本质上要求服务知道UI的细节,这是不可取的(尽管有一些模式可以解决这个问题).

Task定义了一些属性并具有相应的updateXXX方法,例如updateMessage(...)您在示例代码中调用的方法.这些方法可以安全地从任何线程调用,并导致更新要在FX应用程序线程上执行的相应属性.(因此,在您的示例中,您可以安全地将标签的文本绑定到服务的文本messageProperty.)除了确保在正确的线程上执行更新之外,这些updateXXX方法还会限制更新,以便您可以基本上调用它们尽可能多地使FX应用程序线程充满过多的事件要处理:在UI的单个帧中发生的更新将被合并,以便只有最后一次这样的更新(在给定的帧内)是可见的.

valueProperty如果适合您的用例,您可以利用它来更新任务/服务.所以,如果你有一些(最好是不可变的)类来表示解析数据包的结果(让我们调用它PacketData;但也许它就像a一样简单String),你做

public class StatusListener implements Service<PacketData> {

   // ...

   @Override
   protected Task<PacketData> createTask() {
      return new Task<PacketData>() {
          // ...

          @Override
          public PacketData call() {
              // ...
              while (! isCancelled()) { 
                  // receive packet, parse data, and wrap results:
                  PacketData data = new PacketData(...);
                  updateValue(data);
              }
              return null ;
          }
      };
   }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以做到

StatusListener listener = new StatusListener();
listener.valueProperty().addListener((obs, oldValue, newValue) -> {
    // update UI with newValue...
});
listener.start();
Run Code Online (Sandbox Code Playgroud)

请注意,null当服务被取消时,代码会更新该值,因此,在我概述的实现中,您需要确保您的侦听器valueProperty()处理此案例.

另请注意,updateValue()如果它们出现在同一帧渲染中,这将合并连续调用.因此,如果您需要确保处理处理程序中的每个数据,这不是一种合适的方法(尽管通常不需要在FX应用程序线程上执行此类功能).如果您的UI只需要显示后台进程的"最新状态",这是一种很好的方法.

SSCCE展示了这种技术:

import java.util.Random;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class LongRunningTaskExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        CheckBox enabled = new CheckBox("Enabled");
        enabled.setDisable(true);
        CheckBox activated = new CheckBox("Activated");
        activated.setDisable(true);
        Label name = new Label();
        Label value = new Label();

        Label serviceStatus = new Label();

        StatusService service = new StatusService();
        serviceStatus.textProperty().bind(service.messageProperty());

        service.valueProperty().addListener((obs, oldValue, newValue) -> {
            if (newValue == null) {
                enabled.setSelected(false);
                activated.setSelected(false);
                name.setText("");
                value.setText("");
            } else {
                enabled.setSelected(newValue.isEnabled());
                activated.setSelected(newValue.isActivated());
                name.setText(newValue.getName());
                value.setText("Value: "+newValue.getValue());
            }
        });

        Button startStop = new Button();
        startStop.textProperty().bind(Bindings
                .when(service.runningProperty())
                .then("Stop")
                .otherwise("Start"));

        startStop.setOnAction(e -> {
            if (service.isRunning()) {
                service.cancel() ;
            } else {
                service.restart();
            }
        });

        VBox root = new VBox(5, serviceStatus, name, value, enabled, activated, startStop);
        root.setAlignment(Pos.CENTER);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private static class StatusService extends Service<Status> {
        @Override
        protected Task<Status> createTask() {
            return new Task<Status>() {
                @Override
                protected Status call() throws Exception {
                    Random rng = new Random();
                    updateMessage("Running");
                    while (! isCancelled()) {

                        // mimic sporadic data feed:
                        try {
                            Thread.sleep(rng.nextInt(2000));
                        } catch (InterruptedException exc) {
                            Thread.currentThread().interrupt();
                            if (isCancelled()) {
                                break ;
                            }
                        }

                        Status status = new Status("Status "+rng.nextInt(100), 
                                rng.nextInt(100), rng.nextBoolean(), rng.nextBoolean());
                        updateValue(status);
                    }
                    updateMessage("Cancelled");
                    return null ;
                }
            };
        }
    }

    private static class Status {
        private final boolean enabled ; 
        private final boolean activated ;
        private final String name ;
        private final int value ;

        public Status(String name, int value, boolean enabled, boolean activated) {
            this.name = name ;
            this.value = value ;
            this.enabled = enabled ;
            this.activated = activated ;
        }

        public boolean isEnabled() {
            return enabled;
        }

        public boolean isActivated() {
            return activated;
        }

        public String getName() {
            return name;
        }

        public int getValue() {
            return value;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ johnco3 [服务](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Service.html)和[Task](http://docs.oracle.com)的大量文档/javase/8/javafx/api/javafx/concurrent/Task.html)推荐阅读; 它有很多例子.后者甚至有一个标题为"修改场景图的任务"的部分. (2认同)