0

我对 Swing 和 AWT 很陌生。虽然我有 Java 开发经验。我正在尝试使用 JFileChooser 读取文件并在我的主要方法中获取内容。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___________________________即使我选择了一个包含大量内容的文件,它也会打印出来。

4

2 回答 2

2

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

现在,还有一些额外的事情需要考虑:

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

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

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();
            }
        });

    }
}
于 2013-06-12T09:01:17.663 回答
1

只需创建一个名为File selectedFile. 您正在使用您的FileChooserinActionListener并且 instatiated in this 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());
于 2013-06-12T08:40:46.053 回答