Java 通过JFrame选择文件并将pathToFile返回到主类

Java 通过JFrame选择文件并将pathToFile返回到主类,java,jframe,Java,Jframe,我试图创建一个简单的表单,它允许用户选择一个文件,然后我想在主类中处理这个文件。但我有一个错误“变量框架是从内部类访问的”。好的,我已经读到,我必须使一个变量final,这给了我“不能给final变量'frame'赋值”,这是正确的。再次阅读stackoverflow,我发现我必须将定义变量放在主过程之前。但在这里,我认为这不是一个好的解决方案,因为我从未见过任何代码示例以这种方式定义变量。但我还是试了一下,还是出错了 public class HelloWorld { //ExcelChoos

我试图创建一个简单的表单,它允许用户选择一个文件,然后我想在主类中处理这个文件。但我有一个错误“变量框架是从内部类访问的”。好的,我已经读到,我必须使一个变量final,这给了我“不能给final变量'frame'赋值”,这是正确的。再次阅读stackoverflow,我发现我必须将定义变量放在主过程之前。但在这里,我认为这不是一个好的解决方案,因为我从未见过任何代码示例以这种方式定义变量。但我还是试了一下,还是出错了

public class HelloWorld {
//ExcelChooseFileFrame frame;
public static void main(String[] args)  {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
final ExcelChooseFileFrame frame;
        public void run() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            frame = new ExcelChooseFileFrame();//Cannot assign a value to final variable 'frame'
        }
    });
}
ExcelChooseFileFrame

public class ExcelChooseFileFrame  extends JFrame {
File file;
public ExcelChooseFileFrame(){
    super("Choose excel");

                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel panel = new JPanel();
                panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

                panel.add(Box.createVerticalGlue());

                final JLabel label = new JLabel("Choosed file");
                label.setAlignmentX(CENTER_ALIGNMENT);
                panel.add(label);

                panel.add(Box.createRigidArea(new Dimension(10, 10)));

                JButton button = new JButton("Show JFileChooser");
                button.setAlignmentX(CENTER_ALIGNMENT);

                button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JFileChooser fileopen = new JFileChooser();
                        int ret = fileopen.showDialog(null, "Open file");
                        if (ret == JFileChooser.APPROVE_OPTION) {
                            file = fileopen.getSelectedFile();
//                                System.out.println(file.getPath());
                            setVisible(false);
                            dispose();
            }
        }
    });

    panel.add(button);
    panel.add(Box.createVerticalGlue());
    getContentPane().add(panel);

    setPreferredSize(new Dimension(260, 220));
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
}
public String getPathToFile() {
    return file.getPath();
}
}
我知道这是一项相当简单的任务,但尽管如此,我还是花了几个小时试图解决它,但仍然没有成功。请告诉我,如何从main获取框架或文件对象。
谢谢大家!

HelloWorld
中,在声明变量的行上初始化该变量:

public final ExcelChooseFileFrame frame = new ExcelChooseFileFrame()

然后消除代码中的赋值。只有当您希望从包外的其他类中引用它时,它才需要是公共的。

如果您声明框架的位置,它不需要是最终的。只有在runnable之外声明它,它才需要是final。