0

JFileChooserを使用する場合、TextAreaにテキストファイルの内容をどのように表示しますか。

4

2 に答える 2

2

ここに1つのサンプルプログラムを見つけてください。ただし、読み取るファイルが長い場合は、常に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 に答える