你好,我有一個類打開一個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.
你期望它是什麼?爲什麼? – 2014-10-19 19:39:12
我希望它是「測試」或任何我在textArea中輸入的內容。我想使用輸入的文本。 – gkmohit 2014-10-19 19:40:31
所以讓它做到這一點。 – 2014-10-19 19:41:26