Java Swing load file into JEditorPane

2019-09-02 02:35发布

I'm trying to write text-editor type application in Java/Swing. I have the FileChooser working and I can print out the contents of the file to the console. I want to load the file into a JEditorPane

When I call setText(), it updates the value of the text (I can print the result of getText, but the actual EditorPane is not refreshing). I've tried calling repaint/revalidate on the JEditorPane, the encapsulating JScrollPane but nothing will refresh the text to what I sent to setText.

Am I missing something?

P.S. The JEditorPane is wrapped inside a JScrollPane, and I have a method in my mainEditor that passes the string to the setText method of the JEditorPane.

      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) ;
            }             
      }

2条回答
The star\"
2楼-- · 2019-09-02 03:30

Form the String into a File reference, convert that to an URL then call setPage(URL).

See here for an example.

查看更多
Ridiculous、
3楼-- · 2019-09-02 03:31

use built-in methods for InputStream for JTextComponents family

JTextCompoents#read();

JTextComponents#write();

查看更多
登录 后发表回答