Java/Development Class/Document HTML

Материал из Java эксперт
Перейти к: навигация, поиск

HTMLDocument: Element Iterator Example

/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class ElementIteratorExample {
  public static void main(String args[]) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage: java ElementIteratorExample input-URL");
    }
    // Load HTML file synchronously
    URL url = new URL(args[0]);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);
    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
      AttributeSet attributes = element.getAttributes();
      Object name = attributes.getAttribute(StyleConstants.NameAttribute);
      if ((name instanceof HTML.Tag)
          && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) {
        // Build up content text as it may be within multiple elements
        StringBuffer text = new StringBuffer();
        int count = element.getElementCount();
        for (int i = 0; i < count; i++) {
          Element child = element.getElement(i);
          AttributeSet childAttributes = child.getAttributes();
          if (childAttributes
              .getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
            int startOffset = child.getStartOffset();
            int endOffset = child.getEndOffset();
            int length = endOffset - startOffset;
            text.append(htmlDoc.getText(startOffset, length));
          }
        }
        System.out.println(name + ": " + text.toString());
      }
    }
    System.exit(0);
  }
}





HTMLEditorKit Demo

/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.text.JTextComponent;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class LoadSync {
  public static void main(String args[]) {
    final String filename = "Test.html";
    JFrame frame = new JFrame("Loading/Saving Example");
    Container content = frame.getContentPane();
    final JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(editorPane);
    content.add(scrollPane, BorderLayout.CENTER);
    editorPane.setEditorKit(new HTMLEditorKit());
    JPanel panel = new JPanel();
    // Setup actions
    Action loadAction = new AbstractAction() {
      {
        putValue(Action.NAME, "Load");
      }
      public void actionPerformed(ActionEvent e) {
        doLoadCommand(editorPane, filename);
      }
    };
    JButton loadButton = new JButton(loadAction);
    panel.add(loadButton);
    content.add(panel, BorderLayout.SOUTH);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
  public static void doLoadCommand(JTextComponent textComponent,
      String filename) {
    FileReader reader = null;
    try {
      System.out.println("Loading");
      reader = new FileReader(filename);
      // Create empty HTMLDocument to read into
      HTMLEditorKit htmlKit = new HTMLEditorKit();
      HTMLDocument htmlDoc = (HTMLDocument) htmlKit
          .createDefaultDocument();
      // Create parser (javax.swing.text.html.parser.ParserDelegator)
      HTMLEditorKit.Parser parser = new ParserDelegator();
      // Get parser callback from document
      HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
      // Load it (true means to ignore character set)
      parser.parse(reader, callback, true);
      // Replace document
      textComponent.setDocument(htmlDoc);
      System.out.println("Loaded");
    } catch (IOException exception) {
      System.out.println("Load oops");
      exception.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException ignoredException) {
        }
      }
    }
  }
}





SimpleAttributeSet Example

/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class SimpleAttributeSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Simple Attributes");
    Container content = frame.getContentPane();
    StyledDocument document = new DefaultStyledDocument();
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    attributes.addAttribute(StyleConstants.CharacterConstants.Bold,
        Boolean.TRUE);
    attributes.addAttribute(StyleConstants.CharacterConstants.Italic,
        Boolean.TRUE);
    // Insert content
    try {
      document.insertString(document.getLength(), "Hello Java",
          attributes);
    } catch (BadLocationException badLocationException) {
      System.err.println("Oops");
    }
    attributes = new SimpleAttributeSet();
    attributes.addAttribute(StyleConstants.CharacterConstants.Bold,
        Boolean.FALSE);
    attributes.addAttribute(StyleConstants.CharacterConstants.Italic,
        Boolean.FALSE);
    attributes.addAttribute(StyleConstants.CharacterConstants.Foreground,
        Color.lightGray);
    // Insert content
    try {
      document.insertString(document.getLength(),
          " - Good-bye Visual Basic", attributes);
    } catch (BadLocationException badLocationException) {
      System.err.println("Oops");
    }
    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





Styled Document

/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class StyledSample {
  public static void main(String args[]) {
    String BOLD_ITALIC = "BoldItalic";
    String GRAY_PLAIN = "Gray";
    JFrame frame = new JFrame("Simple Attributes");
    Container content = frame.getContentPane();
    StyledDocument document = new DefaultStyledDocument();
    Style style = (Style) document.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setBold(style, true);
    StyleConstants.setItalic(style, true);
    document.addStyle(BOLD_ITALIC, null);
    //    style = document.getStyle(StyleContext.DEFAULT_STYLE);
    //    StyleConstants.setBold(style, false);
    //    StyleConstants.setItalic(style, false);
    //    StyleConstants.setForeground(style, Color.lightGray);
    //    document.addStyle(GRAY_PLAIN, null);
    style = document.getStyle(BOLD_ITALIC);
    // Insert content
    try {
      document.insertString(document.getLength(), "Hello Java\n", style);
    } catch (BadLocationException badLocationException) {
      System.err.println("Oops");
    }
    style = document.getStyle(GRAY_PLAIN);
    // Insert content
    try {
      document.insertString(document.getLength(),
          " - Good-bye Visual Basic\n", style);
    } catch (BadLocationException badLocationException) {
      System.err.println("Oops");
    }
    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





Text Tab Sample

/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;
public class TextTabSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tab Attributes");
    Container content = frame.getContentPane();
    StyledDocument document = new DefaultStyledDocument();
    int positions[] = { TabStop.ALIGN_BAR, TabStop.ALIGN_CENTER,
        TabStop.ALIGN_DECIMAL, TabStop.ALIGN_LEFT, TabStop.ALIGN_RIGHT };
    String strings[] = { "\tBAR\n", "\tCENTER\n", "\t3.14159265\n",
        "\tLEFT\n", "\tRIGHT\n" };
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    for (int i = 0, n = positions.length; i < n; i++) {
      TabStop tabstop = new TabStop(150, positions[i], TabStop.LEAD_DOTS);
      try {
        int position = document.getLength();
        document.insertString(position, strings[i], null);
        TabSet tabset = new TabSet(new TabStop[] { tabstop });
        StyleConstants.setTabSet(attributes, tabset);
        document.setParagraphAttributes(position, 1, attributes, false);
      } catch (BadLocationException badLocationException) {
        System.err.println("Oops");
      }
    }
    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}