2014-10-19 58 views
0

你好,我有一個類打開一個JFrame並接受一個文本。但是,當我嘗試獲取文本時,它說它爲空。 每次我點擊按鈕我想讓System.out打印我在textArea中輸入的文本。爲什麼我的輸出每次都是空的?

這是我的第一類:

public class FileReader { 

    FileBrowser x = new FileBrowser(); 
    private String filePath = x.filePath; 

    public String getFilePath(){ 

     return this.filePath; 
    } 

    public static void main(String[] args) { 
     FileReader x = new FileReader(); 
     if(x.getFilePath() == null){ 
      System.out.println("String is null."); 
     } 
     else 
     { 
      System.out.println(x.getFilePath()); 
     } 
    } 
} 

這是一個JFrame這需要在一個靜態的字符串輸入和存儲。

/* 
* This class is used to read the location 
* of the file that the user. 
*/ 
import java.awt.*; 
import java.awt.event.*; 
import java.awt.event.*; 
import javax.swing.*; 


public class FileBrowser extends JFrame{ 

    private JTextArea textArea; 
    private JButton button; 
    public static String filePath; 

    public FileBrowser(){ 
     super("Enter file path to add"); 
     setLayout(new BorderLayout()); 

     this.textArea = new JTextArea(); 
     this.button = new JButton("Add file"); 

     add(this.textArea, BorderLayout.CENTER); 
     add(this.button, BorderLayout.SOUTH); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setSize(300, 100); 
     setVisible(true); 

     this.button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       filePath = new String(textArea.getText()); 
       System.exit(0); 
      } 
     }); 

    } 
} 

但每次我運行這些程序,我得到

String is null. 

enter image description here

+0

你期望它是什麼?爲什麼? – 2014-10-19 19:39:12

+0

我希望它是「測試」或任何我在textArea中輸入的內容。我想使用輸入的文本。 – gkmohit 2014-10-19 19:40:31

+0

所以讓它做到這一點。 – 2014-10-19 19:41:26

回答

3

您是通過怎樣的方式JFrames工作錯了。在關閉代碼之前,JFrame不會停止執行代碼。所以,基本上,您的代碼會創建一個JFrame,然後在用戶可能指定文件之前抓取該對象中的filePath變量。

所以,要解決這個問題,請將輸出文件路徑的代碼移到標準輸出到您擁有的ActionListener。取消撥打System.exit(),然後改用dispose()


更新:你應該有一個的ActionListener驗證碼:

this.button.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     filePath = new String(textArea.getText()); 

     if(filePath == null){ 
      System.out.println("String is null."); 
     } 
     else 
     { 
      System.out.println(filePath); 
     } 

     dispose(); 
    } 
}); 

而且作爲主要的方法:

public static void main(String[] args) 
{ 
    FileBrowser x = new FileBrowser(); 
} 
+0

我把我的main添加到了ActionListener中。但我仍然得到輸出爲空。 另外我該如何使用'dispose()'? – gkmohit 2014-10-19 20:12:18

+1

檢查我的更新。 – 2014-10-19 20:17:16

+0

非常感謝。我有一個更快的問題。如何在另一個課程中使用文本區域中輸入的文本? :/ – gkmohit 2014-10-19 20:22:03

1

你的主要不等待,直到用戶指定了textArea中的文本。您可以通過循環來防止這種行爲,直到textArea中的文本被設置,或者您可以將主函數的邏輯放入ActionListener來處理事件。 繼第二種方法之後,主函數只創建一個新的FileBrowser對象。

相關問題