从服务线程更新JavaFX GUI

时间:2016-02-01 21:21:25

标签: java multithreading javafx

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

我不确定是否需要使用简单的绑定属性(如message),或者我应该将小部件传递给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;
            } 
        };
    }
}

1 个答案:

答案 0 :(得分:5)

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

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

如果适用于您的用例,您可以利用此更新任务/服务的valueProperty。因此,如果你有一些(最好是不可变的)类来表示解析数据包的结果(我们称之为PacketData;但也许它就像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 ;
          }
      };
   }
}

现在你可以做到

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

请注意,当取消服务时,代码会将值更新为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);
    }
}
相关问题