Search code examples
javahtmlswingjtextpanehtml-editor

HTML Page not Showing up in Java Swing JTextPane


I'm trying to experiment with the non-JTextArea Swing text components, and in this code am trying to display a very simple web page in a JTextPane. I'm able to read the web page and able to put it into the JTextPane's document, as shown when I print out the String that returns on calling getText on my HTMLDocument, but nothing shows up in the JTextPane. I feel as though I'm missing something basic. Thanks in advance.

My SSCCE:

import java.awt.*;
import java.io.IOException;
import java.net.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

@SuppressWarnings("serial")
public class TestStyledDoc2 extends JPanel {
   public static final String GETTY_FILE = "http://www.d.umn.edu/~rmaclin/" +
        "gettysburg-address.html";

   private HTMLEditorKit htmlKit = new HTMLEditorKit();
   private HTMLDocument htmlDocument = (HTMLDocument) htmlKit.createDefaultDocument();
   private JTextPane htmlPane = new JTextPane(htmlDocument);

   public TestStyledDoc2() {
      JScrollPane scrollPane1 = new JScrollPane(htmlPane);
      try {
         htmlPane.setEditorKit(htmlKit);
         URL gettyUrl = new URL(GETTY_FILE);
         htmlKit.read(gettyUrl.openStream(), htmlDocument, 0);
         System.out.println(htmlDocument.getText(0, htmlDocument.getLength()));
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (BadLocationException e) {
         e.printStackTrace();
      } 

      scrollPane1.getViewport().setPreferredSize(new Dimension(400, 400));

      setLayout(new BorderLayout());
      add(scrollPane1, BorderLayout.CENTER);
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("TestStyledDoc");
      frame.getContentPane().add(new TestStyledDoc2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

Solution

  • The call of setEditorKit() removes your initially assigned document and replaces it with a new one. Just add another line right after to restore the correct document.

    htmlPane.setEditorKit(htmlKit);
    htmlPane.setDocument(htmlDocument);
    

    or reget the document from your textpane

    htmlPane.setEditorKit(htmlKit);
    htmlDocument = (HTMLDocument) htmlPane.getDocument();