2013-03-23 56 views
2

JavaFX在將文本設置爲文本字段時產生NullPointerexception。 此代碼生成此異常:如何解決javafx-8中的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) 

有什麼解決方法嗎?或者我應該等到發佈?

謝謝。

+0

是否在JavaFX應用程序線程上調用了'invalidate'方法? – jewelsea 2013-03-23 20:22:45

回答

5

據我所知,問題是由於用JavaFX Application Thread調用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尋求幫助。

相關問題