0

我正在尝试使用 JEditorPane(在不可编辑模式下)在框架中打开文本文件。但是,我相信我在设置输入流和输出流时遇到了问题。请查看我的代码并告诉我哪里做错了。


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


public class TextEditor extends JFrame{

private JEditorPane editorpane;
JScrollPane editorScrollPane;
String filename="D:\\abc.txt";
Reader filereader;

public TextEditor()
{       
        editorpane= new JEditorPane();
        editorpane.setEditable(false);

        if (filename != null) 
        {
            try 
            {
                filereader=new FileReader(filename);
                editorpane.setPage(filename);
            }

            catch (IOException e) 
            {
                System.err.println("Attempted to read a bad file " + filename);
            }
         }

        else
        {
            System.err.println("Couldn't find file");
        }

        //Put the editor pane in a scroll pane.
        editorScrollPane = new JScrollPane(editorpane);
            editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        editorScrollPane.setPreferredSize(new Dimension(250, 145));
        editorScrollPane.setMinimumSize(new Dimension(10, 10));

}

public static void main(String[] args) 
{
    TextEditor obj= new TextEditor();
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.setSize(600,600);
    obj.setLocation(100,100);
    obj.setVisible(true);
}
}
4

3 回答 3

6

要将参数作为URLfor JEditorPane.setPage,您可以使用:

File file = new File(filename);
editorpane.setPage(file.toURI().toURL());

也不要忘记将您添加JEditorPane到框架中,以便可以看到它:

add(editorScrollPane);

要查看您正在添加的磁盘错误:

e.printStackTrace();

IOException块。

于 2012-09-18T13:56:37.913 回答
2
editorpane.getEditorKit().read(filereader, editorpane.getDocument(), 0);
于 2012-09-18T13:53:24.203 回答
1

JEdi​​torPane.setPage() 需要一个 URL,包括协议:尝试“file:///D:/abc.txt”。以下代码应该可以工作:

String filename="file:///D:/abc.txt";

public TextEditor()
{
        editorpane= new JEditorPane();
        editorpane.setEditable(false);

        if (filename != null)
        {
            try
            {
                editorpane.setPage(filename);
            }

            catch (IOException e)
            {
                System.err.println("Attempted to read a bad file " + filename );
                e.printStackTrace();
            }
         }

        else
        {
            System.err.println("Couldn't find file");
        }

        //Put the editor pane in a scroll pane.
        editorScrollPane = new JScrollPane(editorpane);
            editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        editorScrollPane.setPreferredSize(new Dimension(250, 145));
        editorScrollPane.setMinimumSize(new Dimension(10, 10));
      getContentPane().add(editorScrollPane);

}
于 2012-09-18T13:51:31.427 回答