0 Replies Latest reply: Jul 5, 2013 6:48 AM by Jörg RSS

    How to write into the head of an HTMLDocument?

    Jörg

      Hello,

       

      I would like to write a comment or a meta tag in an HTMLDocument, but the following attempt fails already in finding the HEAD tag.

      import java.awt.*;
      import java.io.*;
      import javax.swing.*;
      import javax.swing.text.*;
      import javax.swing.text.html.*;
      
      public class WriteIntoHtmlHead {
        HTMLDocument doc;
        HTMLEditorKit kit;
      
       public WriteIntoHtmlHead() {
          JTextPane tp= new JTextPane();
          tp.setContentType("text/html");
          kit= (HTMLEditorKit)tp.getEditorKit();
          doc= (HTMLDocument)kit.createDefaultDocument();
          Element[] roots = doc.getRootElements(); // #0 is the HTML element (No!)
          for (int i=0; i<roots[0].getElementCount(); i++) {
            Element element = roots[0].getElement(i);
            System.out.println(element.getName()); // -> body
          }
          Element head = doc.getElement(doc.getDefaultRootElement(),
                                        StyleConstants.NameAttribute, HTML.Tag.HEAD);
          System.out.println(head); // -> null
          try {
      //      doc.insertAfterStart(head, "<!-- my comment -->");
            doc.insertAfterStart(head, "<meta id=123>");
          }
          catch (BadLocationException e) {
            e.printStackTrace();
          }
          catch (IOException e) {
            e.printStackTrace();
          }
        }
      
        public static void main(String args[]) {
          EventQueue.invokeLater(new Runnable() {
            public void run() {
              new WriteIntoHtmlHead();
            }
          });
        }
      
      }