HTML-страница не отображается в Java Swing JTextPane

Я пытаюсь поэкспериментировать сJTextArea Качайте текстовые компоненты, и в этом коде я пытаюсь отобразить очень простую веб-страницу в JTextPane, Я могу читать веб-страницу и помещать ее в JTextPaneдокумент, как показано, когда я распечатаю строку, которая возвращается при вызове getText на моем HTMLDocument, но ничего не появляется в JTextPane. Я чувствую, что мне не хватает чего-то простого. Заранее спасибо.

Мой 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();
         }
      });
   }
}

2 ответа

Решение

Зов setEditorKit() удаляет ваш изначально назначенный документ и заменяет его новым. Просто добавьте еще одну строку сразу после восстановления правильного документа.

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

или забрать документ из вашей текстовой панели

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

Вам не нужно знать о фактическом наборе редактора или используемом документе:

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

public class EditorPaneLoad extends JFrame
{
    public EditorPaneLoad()
        throws Exception
    {
        FileReader reader = new FileReader("a.html");
//      JEditorPane editor = new JEditorPane();
        JTextPane editor = new JTextPane();
        editor.setContentType( "text/html" );
        editor.setEditable( false );
        editor.read(reader, null);
        System.out.println(editor.getText());
        System.out.println("\n------------\n");
        Document doc = editor.getDocument();
        System.out.println(doc.getText(0, doc.getLength()));
        JScrollPane scrollPane = new JScrollPane( editor );
        scrollPane.setPreferredSize( new Dimension(300, 200) );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
        throws Exception
    {
        EditorPaneLoad frame = new EditorPaneLoad();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
Другие вопросы по тегам