Java 值未存储在变量中

Java 值未存储在变量中,java,jfilechooser,Java,Jfilechooser,这是一个使用JFileChooser的程序: package execute; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swin

这是一个使用JFileChooser的程序:

package execute;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class FCDemo extends JFrame
{
    JFileChooser fc = new JFileChooser();
    private String fileName;

    public FCDemo(String title)
    {
        super(title);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel pnl = new JPanel();
        pnl.setLayout(new GridLayout(2, 1));

        JButton btn = new JButton("JFileChooser.showOpenDialog() Demo");
        ActionListener al;
        al = new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                switch (fc.showOpenDialog(FCDemo.this))
                {
                case JFileChooser.APPROVE_OPTION:
                    fileName=fc.getSelectedFile().getName();
                    JOptionPane.showMessageDialog(FCDemo.this, "Selected: "+fc.getSelectedFile(),"FCDemo",JOptionPane.OK_OPTION);
                    break;

                case JFileChooser.CANCEL_OPTION:
                    JOptionPane.showMessageDialog(FCDemo.this, "Cancelled","FCDemo",JOptionPane.OK_OPTION);
                    break;

                case JFileChooser.ERROR_OPTION:
                    JOptionPane.showMessageDialog(FCDemo.this, "Error","FCDemo",JOptionPane.OK_OPTION);
                }

            }   
        };
        btn.addActionListener(al);
        pnl.add(btn);

        setContentPane(pnl);

        pack();
        setVisible(true);
    }

    public String get_fileName(){
        return fileName;
    }


    public static void main(String[] args)
    {

        FCDemo demo=new FCDemo("filechooser");
        System.out.println("the file name is= "+demo.get_fileName());
    }
}
由于某些原因,所选文件的目录未存储在名为
fileName
的字符串变量中。当我将
文件名
打印到控制台时,我得到空值
有人能帮我解决这个问题吗?

文件名存储正确。在按下初始帧中的按钮之前,尝试观察控制台。输出在您看到FileChooser之前发生。Swing很可能使用额外的线程来绘制UI。在绘制JFrame时并行打印输出。

在选择文件之前执行主线程。这就是文件名被打印为空的原因。要查看所选文件,请尝试使主线程休眠10秒钟。然后选择你的文件。之后,您可以在main中看到所选文件。 使用:


因此,目录存储在变量fileName中?确实,请参见Rahul的回答,它包含详细信息。如果用户选择文件的时间超过10秒,该怎么办?这只是查看所选文件名的一个示例。要获取文件名,使用的方法不正确。您建议我如何获取文件名?@user3189664为此,您可以使用Jpanel扩展您的类。在面板中添加按钮。在main方法中创建框架,并在框架中添加类的对象。这样你就可以继续了。
public static void main(String[] args)
{
    FCDemo demo=new FCDemo("filechooser");
    try {
          Thread.sleep(10000);
    } catch (Exception e) {
        // TODO: handle exception
    }
    System.out.println("the file name is= "+demo.get_fileName());
}