为什么将 TextField 绑定到正在另一个线程上更新的 属性 最终导致应用程序抛出错误?

Why does binding a TextField to a property which is being updated on another thread end up with the application throwing errors?

我有一个 javafx 应用程序,其中有多个选项卡(计时器、秒表、时钟),每个选项卡都有一个单独的控制器,用户可以使用 start/stop 按钮添加和独立启动多个计时器。

我尝试将一个 TextField 绑定到另一个 class MyTimer 的 属性,它跟踪经过的时间,但它最终(在 运行 几秒钟后)开始抛出一个错误。 (如果你检查下面的代码,请注意只有当 "Thread.sleep" 设置为 10ms 时才会发生 - 当我将延迟增加到 100ms 时,它保持 运行 大约一分钟并且没有崩溃 - 我没有进一步测试,因为我想解决根本原因而不是增加延迟)。

让你有个快速的想法: app image

MyTimer class:

    public class MyTimer implements Startable {

...

    private long startNanoTime, storedElapsedTime, totalTime;
    private TimerStates state;
    private StringProperty timerStringProperty = new SimpleStringProperty(DEFAULT_TIMER_STRING_VALUE); 

    public MyTimer() {
        //constructor
    }

    public long getRemainingTime() {
        //returns remaining time
    }

    public StringProperty timerStringPropertyProperty() {
        return timerStringProperty;
    }

    @Override
        public boolean start() {
            if (this.state.isRunning() ) {
                System.out.println("Already running.");
                return false;
            }

            this.startNanoTime = System.nanoTime();
            this.state = TimerStates.RUNNING;

            Runnable startTimerRunnable = new Runnable() {
                @Override
                public void run() {
                    while(state.isRunning()) {
                        timerStringProperty.set(MyFormatter.longMillisecondsTimeToTimeString(getRemainingTime())); //The parameter passed is simply the remaining time formatted to a String
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            Thread daemonTimer = new Thread(startTimerRunnable);
            daemonTimer.setDaemon(true);
            daemonTimer.start();

            return true;
        }
    }

在尝试实现绑定时,我尝试将一个在应用程序启动时无需任何用户交互就存在的默认 TextProperty 绑定到 属性,表示从 MyTimer class 到控制器中的值:

public class TimerTabController {
    ...

    @FXML
    private Tab timerTab;
    @FXML
    private HBox defaultTimerHBox;
    @FXML
    private TextField defaultTimerTextField;

    private Map<HBox, MyTimer> timers = new HashMap<>();

    @FXML
    protected void initialize() {
        MyTimer defaultTimer = new MyTimer();
        timers.put(defaultTimerHBox, defaultTimer);
        defaultTimerTextField.textProperty().bind(defaultTimer.timerStringPropertyProperty());
    }
}

启动它的 Main 方法是相当标准的,但无论如何我都会包括它:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("fxml/mainWindow.fxml"));
        primaryStage.setTitle("Mortimer");
        primaryStage.setScene(new Scene(root, 800, 700));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

最后,堆栈跟踪: 首先,有这个:

Exception in thread "Thread-3" java.lang.NullPointerException
    at javafx.graphics/com.sun.javafx.text.PrismTextLayout.createLine(PrismTextLayout.java:893)
    at javafx.graphics/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1193)
    at javafx.graphics/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:222)
    at javafx.graphics/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:245)
    at javafx.graphics/javafx.scene.text.Text.getLogicalBounds(Text.java:430)
    at javafx.graphics/javafx.scene.text.Text.getYRendering(Text.java:1085)
    at javafx.graphics/javafx.scene.text.Text.access00(Text.java:127)
    at javafx.graphics/javafx.scene.text.Text$TextAttribute.computeValue(Text.java:1764)
    at javafx.graphics/javafx.scene.text.Text$TextAttribute.computeValue(Text.java:1756)
    at javafx.base/javafx.beans.binding.ObjectBinding.get(ObjectBinding.java:151)
    at javafx.base/javafx.beans.binding.ObjectExpression.getValue(ObjectExpression.java:49)
    at javafx.base/javafx.beans.property.ObjectPropertyBase.get(ObjectPropertyBase.java:133)
    at javafx.controls/javafx.scene.control.skin.TextFieldSkin.lambda$new(TextFieldSkin.java:252)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:136)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
    at javafx.base/javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:106)
    at javafx.base/javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:113)
    at javafx.base/javafx.beans.property.ObjectPropertyBase.access[=14=]0(ObjectPropertyBase.java:52)
    at javafx.base/javafx.beans.property.ObjectPropertyBase$Listener.invalidated(ObjectPropertyBase.java:234)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:136)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
    at javafx.base/javafx.beans.binding.ObjectBinding.invalidate(ObjectBinding.java:170)
    at javafx.graphics/javafx.scene.text.Text.doGeomChanged(Text.java:842)
    at javafx.graphics/javafx.scene.text.Text.access0(Text.java:127)
    at javafx.graphics/javafx.scene.text.Text.doGeomChanged(Text.java:158)
    at javafx.graphics/com.sun.javafx.scene.shape.TextHelper.geomChangedImpl(TextHelper.java:106)
    at javafx.graphics/com.sun.javafx.scene.NodeHelper.geomChanged(NodeHelper.java:137)
    at javafx.graphics/javafx.scene.text.Text.needsTextLayout(Text.java:266)
    at javafx.graphics/javafx.scene.text.Text.needsFullTextLayout(Text.java:261)
    at javafx.graphics/javafx.scene.text.Text.access0(Text.java:127)
    at javafx.graphics/javafx.scene.text.Text.invalidated(Text.java:461)
    at javafx.base/javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:110)
    at javafx.base/javafx.beans.property.StringPropertyBase.access[=14=]0(StringPropertyBase.java:50)
    at javafx.base/javafx.beans.property.StringPropertyBase$Listener.invalidated(StringPropertyBase.java:231)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:136)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
    at javafx.base/javafx.beans.binding.StringBinding.invalidate(StringBinding.java:169)
    at javafx.base/com.sun.javafx.binding.BindingHelperObserver.invalidated(BindingHelperObserver.java:52)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:348)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.fireValueChangedEvent(TextInputControl.java:1430)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.markInvalid(TextInputControl.java:1434)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.controlContentHasChanged(TextInputControl.java:1373)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.access00(TextInputControl.java:1341)
    at javafx.controls/javafx.scene.control.TextInputControl.lambda$new[=14=](TextInputControl.java:144)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:136)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
    at javafx.controls/javafx.scene.control.TextField$TextFieldContent.insert(TextField.java:87)
    at javafx.controls/javafx.scene.control.TextInputControl.replaceText(TextInputControl.java:1244)
    at javafx.controls/javafx.scene.control.TextInputControl.filterAndSet(TextInputControl.java:1211)
    at javafx.controls/javafx.scene.control.TextInputControl.access0(TextInputControl.java:80)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.doSet(TextInputControl.java:1451)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.access00(TextInputControl.java:1341)
    at javafx.controls/javafx.scene.control.TextInputControl$TextProperty$Listener.invalidated(TextInputControl.java:1474)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:136)
    at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
    at javafx.base/javafx.beans.property.StringPropertyBase.fireValueChangedEvent(StringPropertyBase.java:104)
    at javafx.base/javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:111)
    at javafx.base/javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:145)
    at javafx.base/javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:50)
    at MorTimer/sample.MyTimer.run(MyTimer.java:106)
    at java.base/java.lang.Thread.run(Thread.java:834)

然后下面的错误不断重复:

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at javafx.graphics/com.sun.javafx.text.PrismTextLayout.getRuns(PrismTextLayout.java:235)
    at javafx.graphics/javafx.scene.text.Text.getRuns(Text.java:389)
    at javafx.graphics/javafx.scene.text.Text.updatePGText(Text.java:1460)
    at javafx.graphics/javafx.scene.text.Text.doUpdatePeer(Text.java:1490)
    at javafx.graphics/javafx.scene.text.Text.access0(Text.java:127)
    at javafx.graphics/javafx.scene.text.Text.doUpdatePeer(Text.java:137)
    at javafx.graphics/com.sun.javafx.scene.shape.TextHelper.updatePeerImpl(TextHelper.java:75)
    at javafx.graphics/com.sun.javafx.scene.NodeHelper.updatePeer(NodeHelper.java:102)
    at javafx.graphics/javafx.scene.Node.syncPeer(Node.java:710)
    at javafx.graphics/javafx.scene.Scene$ScenePulseListener.synchronizeSceneNodes(Scene.java:2366)
    at javafx.graphics/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2512)
    at javafx.graphics/com.sun.javafx.tk.Toolkit.lambda$runPulse(Toolkit.java:412)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:411)
    at javafx.graphics/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:438)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:519)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:499)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:492)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit(QuantumToolkit.java:320)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:834)
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at javafx.graphics/javafx.scene.Scene$ScenePulseListener.synchronizeSceneNodes(Scene.java:2365)
    at javafx.graphics/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2512)
    at javafx.graphics/com.sun.javafx.tk.Toolkit.lambda$runPulse(Toolkit.java:412)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:411)
    at javafx.graphics/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:438)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:519)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:499)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:492)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit(QuantumToolkit.java:320)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:834)

当我在 MyTimer.start() 函数中使用 Platform.runLater() 时,它确实起作用了,就像这样:

    Runnable startTimerRunnable = new Runnable() {
        @Override
        public void run() {
            while(state.isRunning()) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        timerStringProperty.set(MyFormatter.longMillisecondsTimeToTimeString(getRemainingTime()));
                    }
                });
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    Thread daemonTimer = new Thread(startTimerRunnable);
    daemonTimer.setDaemon(true);
    daemonTimer.start();

但是这样用Platform.runLater好像不对,还是可以的?我知道 GUI 不应该在 FX 线程之外更新,但我认为绑定属性可以解决这个问题——更新绑定到 GUI 元素的 属性 不需要在 FX 线程中进行,作为绑定的一部分,GUI 更新确实会在 FX 线程上得到正确处理...

最终,我的解决方案似乎工作得相当好,是不使用绑定,而是定期更新控制器本身的字段(以下方法在选项卡本身的 "onSelectionChanged" 上调用)- 但是我想知道如何使绑定工作,因为绑定似乎是更好的做法。 不管怎样,下面是同样有效的代码:

public void startTimeFieldUpdates() {
    Runnable timeTracker = new Runnable() {
        @Override
        public void run() {
            while(timerTab.isSelected()) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        for (HBox hBox : timers.keySet()) {
                            if (hBox.getChildren().get(1) instanceof TextField) {
                                TextField currentField = (TextField) hBox.getChildren().get(1);
                                currentField.setText(MyFormatter.longMillisecondsTimeToTimeString(
                                        timers.get(hBox).getRemainingTime())
                                                    );
                            }
                        }
                    }
                });

                try {
                    Thread.sleep(10);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }

            }
        }
    };
    Thread daemonStopwatch = new Thread(timeTracker);

    daemonStopwatch.setDaemon(true);
    daemonStopwatch.start();
}

那么我的问题是,解决这个问题的正确方法是什么?

正如我的问题的评论中所发布的那样,答案确实是 属性 绑定使用的侦听器最终 运行 在 属性 本身更新的同一线程上 -因此,为避免出现问题,需要在 Java FX 应用程序线程上更新绑定属性(或者应该寻求其他解决方案,就像我的情况一样)。

对我有用的解决方案 - 正如我的问题的评论中提到的,我查看了 AnimationTimer 是什么,它似乎正是我正在寻找的并且完美地工作。

如果对某人有帮助,这是我的实现:

import ...

public class TimerTabController {
    public static final int TIMER_HBOX_TEXTFIELD_INDEX = 1;
    public static final int TIMER_HBOX_STARTSTOP_BUTTON_INDEX = 2;

    @FXML
    private Tab timerTab;
    @FXML
    private HBox defaultTimerHBox;
    @FXML
    private TextField defaultTimerTextField;

    private Map<HBox, MyTimer> timers = new HashMap<>();

    private AnimationTimer timerTabAnimationTimer = new AnimationTimer() {
        @Override
        public void handle(long l) {
        //the GUI updates go here
            for (HBox hBox : timers.keySet()) {
                if (hBox.getChildren().get(TIMER_HBOX_TEXTFIELD_INDEX) instanceof TextField) {
                    TextField currentField = (TextField) hBox.getChildren().get(TIMER_HBOX_TEXTFIELD_INDEX);
                    currentField.setText(MyFormatter.longMillisecondsTimeToTimeString(
                            timers.get(hBox).getRemainingTime())
                                        );
                }
            }
        }
    };

    @FXML
    protected void initialize() {
        timers.put(defaultTimerHBox, new MyTimer());
    }

    @FXML
    void handleSelectionChanged() { //triggered by changing tab selection
        if (timerTab.isSelected()) {
            timerTabAnimationTimer.start();
        } else {
            timerTabAnimationTimer.stop();
        }
    }

    //some more code
}