0

使用 JFileChooser 时如何在 TextArea 中显示文本文件的内容。

4

2 回答 2

2

在这里找到一个示例程序,为您提供帮助,但如果要读取的文件很长,请始终使用SwingWorker的帮助:

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ReadFileExample
{
    private BufferedReader input;
    private String line;
    private JFileChooser fc;

    public ReadFileExample()
    {
        line = new String();
        fc = new JFileChooser();        
    }

    private void displayGUI()
    {
        final JFrame frame = new JFrame("Read File Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JTextArea tarea = new JTextArea(10, 10);      

        JButton readButton = new JButton("OPEN FILE");
        readButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                int returnVal = fc.showOpenDialog(frame);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would open the file.
                    try
                    {
                        input = new BufferedReader(
                                new InputStreamReader(
                                new FileInputStream(
                                file)));
                        tarea.read(input, "READING FILE :-)");      
                    }
                    catch(Exception e)
                    {       
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("Operation is CANCELLED :(");
                }
            }
        });

        frame.getContentPane().add(tarea, BorderLayout.CENTER);
        frame.getContentPane().add(readButton, BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ReadFileExample().displayGUI();
            }
        });
    }
}
于 2012-06-11T13:54:16.917 回答
1

您的问题不清楚,但我假设您想将 JTextArea 添加到 JFileChooser 以便它可以像文件预览面板一样工作。

您可以使用setAccessory()方法将 JTextArea 添加到 JFileChooser。

JFileChooser 上的本教程展示了如何在附件显示文件中的图像而不是文件中的文本时执行类似的操作。

您需要小心处理不包含文本的文件,或者太大的文件,或者由于权限而无法打开的文件等。要正确处理需要付出很多努力。

于 2012-06-11T21:05:53.540 回答