gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:49:17 36 4
gpt4 key购买 nike

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

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

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

MyTimer 类:

    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;
}
}

在尝试实现绑定(bind)时,我尝试将在应用程序启动时没有任何用户交互的情况下存在的一个默认 TextProperty 绑定(bind)到表示从 MyTimer 类到 Controller 中的值的剩余时间的属性:
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.access$4400(Text.java:127)
at javafx.graphics/javafx.scene.text.Text$TextAttribute$11.computeValue(Text.java:1764)
at javafx.graphics/javafx.scene.text.Text$TextAttribute$11.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$4(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$000(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.access$500(Text.java:127)
at javafx.graphics/javafx.scene.text.Text$1.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.access$900(Text.java:127)
at javafx.graphics/javafx.scene.text.Text$3.invalidated(Text.java:461)
at javafx.base/javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:110)
at javafx.base/javafx.beans.property.StringPropertyBase.access$000(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.access$1600(TextInputControl.java:1341)
at javafx.controls/javafx.scene.control.TextInputControl.lambda$new$0(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.access$900(TextInputControl.java:80)
at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.doSet(TextInputControl.java:1451)
at javafx.controls/javafx.scene.control.TextInputControl$TextProperty.access$1200(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$1.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.access$100(Text.java:127)
at javafx.graphics/javafx.scene.text.Text$1.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$2(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$11(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$3(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$2(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$11(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$3(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 线程之外更新,但我认为绑定(bind)属性会解决这个问题 - 更新绑定(bind)到 GUI 元素的属性不需要在 FX 线程中进行,并且 GUI 更新作为绑定(bind)的一部分,确实会在 FX 线程上正确处理......

最终,我似乎运作良好的解决方案是不使用绑定(bind),而是定期更新 Controller 本身中的字段(以下方法在选项卡本身的“onSelectionChanged”上调用) - 但我想知道如何制作绑定(bind)工作,因为绑定(bind)似乎是更好的做法。
无论如何,这是也可以工作的代码:
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();
}

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

最佳答案

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

对我有用的解决方案 - 正如我对问题的评论中提到的,我查看了 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
}

关于java - 为什么将 TextField 绑定(bind)到正在另一个线程上更新的属性最终会导致应用程序抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513866/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com