Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JEditorPane打开文本文件_Java_Swing_User Interface_Input - Fatal编程技术网

Java 使用JEditorPane打开文本文件

Java 使用JEditorPane打开文本文件,java,swing,user-interface,input,Java,Swing,User Interface,Input,我试图在不可编辑模式下使用JEditorPane打开框架中的文本文件。然而,我相信我在设置输入流和输出流时遇到了问题。请看一下我的代码,告诉我哪里做错了 JEditorPane.setPage需要一个URL,包括协议:tryfile:///D:/abc.txt. 以下代码应该可以工作: String filename="file:///D:/abc.txt"; public TextEditor() { editorpane= new JEditorPane();

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


JEditorPane.setPage需要一个URL,包括协议:tryfile:///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);

}
要将参数作为JEditorPane.setPage的URL获取,可以使用:

File file = new File(filename);
editorpane.setPage(file.toURI().toURL());
另外,不要忘记将您的JEditorPane添加到框架中,以便可以看到:

add(editorScrollPane);
要查看要添加的磁盘错误,请执行以下操作:

e.printStackTrace();

到IOException块。

即使按照您所说的操作,仍然会出现相同的错误消息:试图读取错误的文件:\D:\abc.txt您还需要删除FileReader的创建-您无论如何都不使用它,它将抛出IOError,因为它需要纯文件名,而不是URL,您还需要添加getContentPane.addeditorScrollPane;在TextEditor构造函数的末尾,否则将看不到任何内容…仍然是相同的错误:尝试读取错误文件:\D:\abc.txt仍然是相同的错误:尝试读取错误文件:\D:\abc.txt是的,文件存在。通过在命令提示符下执行此操作,我可以打开该文件:D:\>abc.txtNow在您提供了大量帮助之后,错误消息消失了。但我的框架仍然无法打开文件。只是出现了一个空白框。知道了。非常感谢,先生!!您应该打印IOException的消息。这将给你一个真实的提示:访问被拒绝?找不到文件?磁盘错误?谢谢你的提示。现在错误消息是:java.io.FileNotFoundException:file:\D:\abc.txt文件名、目录名或卷标语法不正确file:///D:/abc.txtpossible 副本
add(editorScrollPane);
e.printStackTrace();