0

我正在尝试用 Java/Swing 编写文本编辑器类型的应用程序。我有 FileChooser 工作,我可以将文件的内容打印到控制台。我想将文件加载到 JEditorPane

当我调用 setText() 时,它会更新文本的值(我可以打印 getText 的结果,但实际的 EditorPane 没有刷新)。我尝试在 JEditorPane 上调用 repaint/revalidate,即封装的 JScrollPane,但没有任何内容会将文本刷新为我发送给 setText 的内容。

我错过了什么吗?

PS JEditorPane 被包裹在一个 JScrollPane 中,我的 mainEditor 中有一个方法将字符串传递给 JEditorPane 的 setText 方法。

      if (r == JFileChooser.APPROVE_OPTION) 
      {
          FileInputStream fis;
          BufferedReader br;
          try
            {
                fis = new FileInputStream( 
                      chooser.getSelectedFile() ) ;
                br  = new BufferedReader( 
                      new InputStreamReader( fis ) ) ;
                String read ;
                StringBuffer text = new StringBuffer() ;
                while( ( read = br.readLine() ) != null ) 
                {
                   text.append( read ).append( "\n" ) ;
                }
                Main.frame.mainEditor.setText( text.toString() ) ;
                Main.frame.mainEditor.revalidate();
            }
            catch( IOException e1 ) 
            {
                JOptionPane.showMessageDialog( this , 
                    "Error in File Operation" ,
                    "Error in File Operation" , 
                    JOptionPane.INFORMATION_MESSAGE) ;
            }             
      }
4

2 回答 2

4

形成参考,将其转换为Stringthen调用。 FileURLsetPage(URL)

有关示例,请参见此处。

于 2012-03-28T11:24:24.880 回答
3

为 JTextComponents 系列使用 InputStream 的内置方法

JTextCompoents#read();

JTextComponents#write();

于 2012-03-28T11:29:04.490 回答