2014-10-19 61 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对象。

相关问题