JFileChooser没有将文件名返回给main方法

时间:2013-06-12 08:25:34

标签: java swing awt jfilechooser

我对Swing和AWT很新。虽然我有Java开发经验。我正在尝试使用JFileChooser读取文件并获取我的main方法中的内容。 Swing和AWT的所有大师请帮我确定我错过了什么。

这是我的代码:

package com.ui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

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

public class HomeScreen extends JFrame
{
    private static final long serialVersionUID = -7604272718213756686L;

    String fileContent;
    final JFileChooser fc = new JFileChooser();
    public HomeScreen()
    {
        super("Home Screen");
        setLayout(new FlowLayout());
        setSize(500,500);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        // Button to open file
        final JButton button = new JButton("Select File");
        button.addActionListener
        (
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    int ret = fc.showDialog(button.getParent(), "Open");
                    if(ret == JFileChooser.APPROVE_OPTION)
                    {
                        File f = fc.getSelectedFile();
                         BufferedReader br;
                        try {
                            br = new BufferedReader(new FileReader(f));
                            String st ="";
                            StringBuilder sb = new StringBuilder();
                            while((st=br.readLine())!=null)
                            {
                                sb.append(st);
                            }
                            fileContent = sb.toString();

                        } catch (FileNotFoundException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                }
            }
        );

        System.out.println(fc.getSelectedFile()+" _____________________");
        add(button);
    }
    public static void main(String[] args)
    {
        HomeScreen screen = new HomeScreen();
    }
}

即使我选择包含大量内容的文件,也会打印null___________________________

2 个答案:

答案 0 :(得分:2)

您的System.out.println()语句不在相应的代码块中。你把它放在你的UI初始化方法(这里是你的构造函数)而不是actionPerformed方法中。

现在,还有一些需要考虑的事项:

  • 与Swing相关的所有操作必须在EDT中完成(例如使用SwingUtilities.invokeLater
  • JFrame.setVisible(true)应该是您的UI初始化代码的最后一条语句
  • 如果你加载大文件,你应该考虑将文件的加载移动到另一个线程而不是EDT(事件调度线程),以避免GUI冻结(SwingWorker通常对此有帮助)

这是您的代码的更新版本(我添加了一个textarea来显示加载的内容):

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class HomeScreen extends JFrame {
    private static final long serialVersionUID = -7604272718213756686L;

    String fileContent;
    final JFileChooser fc = new JFileChooser();

    private JTextArea textArea;

    public HomeScreen() {
        super("Home Screen");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        // Button to open file
        final JButton button = new JButton("Select File");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int ret = fc.showDialog(button.getParent(), "Open");
                if (ret == JFileChooser.APPROVE_OPTION) {
                    File f = fc.getSelectedFile();
                    System.out.println(fc.getSelectedFile() + " _____________________");
                    BufferedReader br;
                    try {
                        br = new BufferedReader(new FileReader(f));
                        String st = "";
                        StringBuilder sb = new StringBuilder();
                        while ((st = br.readLine()) != null) {
                            sb.append(st);
                        }
                        fileContent = sb.toString();
                        textArea.setText(fileContent);
                    } catch (FileNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }
            }
        });
        textArea = new JTextArea(24, 40);
        textArea.setLineWrap(true);
        textArea.setEditable(false);
        add(new JScrollPane(textArea));
        add(button, BorderLayout.SOUTH);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                HomeScreen screen = new HomeScreen();
            }
        });

    }
}

答案 1 :(得分:1)

只需创建一个名为File selectedFile的新类变量。您在FileChooser中使用了ActionListener并在此Listener中进行了设置,因此您无法从中获取文件名,您必须将所选文件保存到类变量中叫selectedFile

编辑: 您可以通过抽象操作处理它:

public class FileChooserAction extends AbstractAction
{
  @Override
  public void actionPerformed(ActionEvent e)
  {
    JFileChooser fc = new JFileChooser;
    int result = fc.showDialog(...);
    if(result == JFileChooser.APPROVE_OPTION)
    {
      System.out.println(fc.getSelectedFile().getAbsolutePath());
    }
  }
}

然后在按钮上添加一个新的Action(按钮的setAction()方法):

setAction(new FileChooserAction());