java - 为什么我的输出每次都是null?

标签 java swing

您好,我有一个类可以打开 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

最佳答案

您误解了 JFrame 的工作方式。 JFrame 在关闭之前不会停止代码的执行。因此,基本上,您的代码会创建一个 JFrame,然后在用户可能指定文件之前获取该对象中的 filePath 变量。

因此,要解决此问题,请将输出文件路径到 stdout 的代码移动到您拥有的 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();
}

关于java - 为什么我的输出每次都是null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26454539/

相关文章:

java - 使用 Spring MVC 的 JAXB 注释

java - 双击 JSplitPane 时如何移动它的分隔线?

java - JTable 中的垂直滚动条

java - 如何禁用结果集中显示的 Jtable 的单元格编辑

java - Swing 事件未向上传递到基础组件

Java 使用 2 个制表符拆分字符串

java - 使用 Java 输入/输出计算 - 小数

java - 以编程方式设置 logback.xml 路径

java - 调用 Window.setVisible() 时出现 NullPointerException

java - 如何在 firebase android 中查询类似云函数中的数据库触发器