2013-03-31 26 views
3

這是我的代碼,非常簡單,它只是在中心創建一個JFrame,其中JTextAreaJTextArea始終爲空?

if(!txtSource.getText().trim().equals("") && txtSource != null)

即使當我輸入文本到JTextArea中永不滿足。

我只想執行methodA()如果JTextArea有一些文本。

private Container content; 
private JTextArea txtSource; 

public Test() { 
    this.setTitle("Test"); 
    this.setSize(600,200); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setLayout(new BorderLayout()); 
    content = this.getContentPane(); 
    content.add(getTextArea(), BorderLayout.CENTER); 
    content.add(button(), BorderLayout.SOUTH); 
    this.setVisible(true); 
} 

private JTextArea getTextArea() { 
    JTextArea txtSource = new JTextArea(20, 80); 
    return txtSource; 
} 

private JButton button() { 

    JButton btn = new JButton("Click me"); 

    btn.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      if(!txtSource.getText().trim().equals("") && txtSource != null) { 
       methodA(); 
      } else { 
       System.out.println("Please paste your script in."); 
     } 
    } 
} 

請幫我在這裏...

+1

'txtSource!= null'最好在左邊。 – Maroun

+0

當我輸入一些文本時,它仍然只是執行'System.out.println(「請將你的腳本粘貼到」中);' – Ciphor

回答

7

shadowingtxtSource變量,與

txtSource = new JTextArea(20, 80); 
+3

+1 nice catch;) –

+0

他的意思是「陰影」在構造函數或方法內聲明txtSource變量,然後初始化重新聲明的變量,您將初始化一個變量,該變量的作用域僅限於方法或構造函數,並且會將類字段留空。正如他所表明的,解決方案是不要在方法或構造函數中重新聲明變量。確保繼續並在那裏初始化變量,但是在類字段上,而不是在局部變量上。 1+ –

+1

鏈接添加解釋影子 – Aubin

2

這可能是因爲你從來沒有初始化txtSource取代

JTextArea txtSource = new JTextArea(20, 80); 

。當然你聲明它,但僅僅因爲getTextArea()的返回值被稱爲txtSource不會像這樣分配類變量。

test()方法中,您應該將this.txtSource指定爲getTextArea(),然後將其添加到容器中。