2011-07-25 40 views
0

這是我班的構造函數。使用以下代碼:爲什麼我在這裏得到例外?

public tester { 
    setTitle("tester"); 
    initComponents(); 
    jTextArea6.setEditable(false); 
    jEditorPane1.setEditable(false); 
} 

每件事情都很好。但有了這個代碼,

public tester() { 
    setTitle("tester"); 
    jTextArea6.setEditable(false); 
    jEditorPane1.setEditable(false); 
    initComponents(); 

} 

我得到以下異常:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
at tester.tester.<init>(tester.java:31) 
at tester.tester$35.run(tester.java:1389) 
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) 
at java.awt.EventQueue.dispatchEvent(EventQueue.java:660) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211) 
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105) 
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) 

爲什麼會是這樣?

+0

也許你正在嘗試設置不存在的可編輯(false)對象? – ascanio

+0

爲了更清晰起見,請考慮發佈[SSCCE](http://pscode.org/sscce.html)。如果這個問題已經這樣做了,那麼正在回答的人就不必妄下結論。 –

回答

7

沒有看到其餘的代碼(特別是initComponents的定義,加上字段的定義),不可能100%確定。

但幾乎可以肯定的是,initComponents()方法設置的值爲jTextArea6和/或jEditorPane1。在第二個示例中,您試圖在設置之前取消引用這些字段;這意味着它們的默認值爲null,所以當您嘗試調用它們上的方法時會引發NullPointerException。

顯然,一個解決辦法是離開的事情,因爲他們,或許還有一個註釋說明

// Note - this method call initialises the fields. DO NOT REORDER!!! 

但是一個更好的解決辦法是讓編譯器檢查這些東西給你。如果這兩個字段永遠不會改變(即它們在構造函數中一勞永逸地設置),那麼你可以並且可以證明它們應該聲明它們final。除此之外,其他人非常清楚,他們不必考慮這些字段可能發生變化,這意味着它們不會有最初分配的默認值,並且編譯器不會讓您在它們尚未解除引用之前對其進行解引用被分配。

+0

我正在使用netbeans作爲我的程序。它自動放置init方法。init實際上做了什麼? – saplingPro

+0

@grassPro - 不知道,你是源代碼。 :) –

0

在initcomponents中創建這些對象?因此,應該先調用?

0

因爲在initComponents();您發出的對象爲 jTextArea6 jEditorPane1

4

因爲jTextArea6jEditorPane1正在初始化爲initComponents。在此之前你無法訪問它們 - 它們是空的。這就是爲什麼你會得到例外。

0
public tester() { 
    setTitle("tester"); 
    jTextArea6.setEditable(false); //jTextArea6 might be null 
    jEditorPane1.setEditable(false); //jEditorPane1 might be null 
    initComponents(); //I assume you're creating your components here, thus jTextArea6 and jEditorPane1 would be non-null after this line only 
} 
0

最有可能,因爲該方法initComponents()初始化變量jTextArea6和/或jEditorPane1。在初始化之前調用方法拋出一個NullPointerException

相關問題