【问题标题】:How to fix NullPointerException in javafx-8如何修复 javafx-8 中的 NullPointerException
【发布时间】:2013-03-23 16:56:06
【问题描述】:

JavaFX 在将文本设置为文本字段时生成NullPointerexception。 此代码产生此异常:

public void invalidate() {
    model.getLock().lock();
    try {
        memoryDisplayTextField.setText(model.getMemory() != 0 ? "M" : "");
        mainDisplayTextField.setText(model.getDisplayText());
    } finally {
        model.getLock().unlock();
    }
}

堆栈跟踪如下:

java.lang.NullPointerException
at com.sun.javafx.text.TextLayout.layout(TextLayout.java:1365)
at com.sun.javafx.text.TextLayout.ensureLayout(TextLayout.java:174)
at com.sun.javafx.text.TextLayout.getBounds(TextLayout.java:197)
at javafx.scene.text.Text.getLogicalBounds(Text.java:387)
at javafx.scene.text.Text.impl_computeGeomBounds(Text.java:1182)
at javafx.scene.Node.updateGeomBounds(Node.java:3322)
at javafx.scene.Node.getGeomBounds(Node.java:3275)
at javafx.scene.Node.getLocalBounds(Node.java:3257)
at javafx.scene.Node.updateTxBounds(Node.java:3335)
at javafx.scene.Node.getTransformedBounds(Node.java:3175)
at javafx.scene.Node.updateBounds(Node.java:504)
at javafx.scene.Parent.updateBounds(Parent.java:1643)
at javafx.scene.Parent.updateBounds(Parent.java:1643)
at javafx.scene.Parent.updateBounds(Parent.java:1643)
at javafx.scene.Parent.updateBounds(Parent.java:1643)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2268)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:352)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:511)
at com.sun.javafx.tk.quantum.QuantumToolkit$12.run(QuantumToolkit.java:379)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)

有什么解决方法吗?还是我应该等到发布?

谢谢。

【问题讨论】:

  • 您的invalidate 方法是否在JavaFX 应用程序线程上被调用?

标签: javafx java-8


【解决方案1】:

据我了解,问题是由 JavaFX 应用程序线程中的 setText 方法引起的,所以 用Platform.runLater() 包裹它可以解决这个问题。

 public void invalidate() {
    Platform.runLater(() -> {
        model.getLock().lock();
        try {
            memoryDisplayTextField.setText(model.getMemory() != 0 ? "M" : "");
            mainDisplayTextField.setText(model.getDisplayText());
        } finally {
            model.getLock().unlock();
        }
    });
}

PS 感谢 jewelsea 的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 2020-11-26
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2020-12-18
    • 2022-01-05
    相关资源
    最近更新 更多