Example usage for javax.swing.text.html HTMLEditorKit HTMLEditorKit

List of usage examples for javax.swing.text.html HTMLEditorKit HTMLEditorKit

Introduction

In this page you can find the example usage for javax.swing.text.html HTMLEditorKit HTMLEditorKit.

Prototype

public HTMLEditorKit() 

Source Link

Document

Constructs an HTMLEditorKit, creates a StyleContext, and loads the style sheet.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    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);// w w w  .j  av a  2  s .c o m

    Element element;
    ElementIterator iterator = new ElementIterator(htmlDoc);
    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.P)) {
            // Build up content text as it may be within multiple elements
            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;
                    System.out.println(htmlDoc.getText(startOffset, length));
                }
            }
        }
    }
}

From source file:ReplaceReader.java

public static void main(String[] args) {
    try {/*from  w w  w  .  ja v  a2s  . c om*/
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new JFrame("JEditorPane with Custom Reader");
    JEditorPane ep = new JEditorPane();
    f.getContentPane().add(new JScrollPane(ep));
    f.setSize(400, 300);
    f.setVisible(true);

    HTMLEditorKit kit = new HTMLEditorKit() {
        public Document createDefaultDocument() {
            HTMLDocument doc = new CustomHTMLDocument(getStyleSheet());
            doc.setAsynchronousLoadPriority(4);
            doc.setTokenThreshold(100);
            return doc;
        }
    };
    ep.setEditorKit(kit);

    try {
        Document doc = ep.getDocument();
        doc.putProperty("IgnoreCharsetDirective", new Boolean(true));
        kit.read(new FileReader(args[0]), doc, 0);
    } catch (Exception e) {
        System.out.println("Exception while reading HTML " + e);
    }
}

From source file:LoadSync.java

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);/*from www.  j a  v a  2  s . c  o m*/
    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);
}

From source file:ElementIteratorExample.java

public static void main(String args[]) throws Exception {

    if (args.length != 1) {
        System.err.println("Usage: java ElementIteratorExample input-URL");
    }/*from   w  ww .  j a v  a 2  s  . c  o  m*/

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

From source file:Main.java

public Main() {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setContentType("text/HTML");
    editorPane.setEditorKit(new HTMLEditorKit());
    editorPane.setText("<hr>Welcome to <b>java2s.com!</b><hr>");
    JToolBar bar = new JToolBar();
    bar.add(new StyledEditorKit.ForegroundAction("Red", Color.red));
    bar.add(new StyledEditorKit.ForegroundAction("Blue", Color.blue));
    bar.add(new StyledEditorKit.FontSizeAction("12", 12));
    bar.add(new StyledEditorKit.FontSizeAction("14", 14));
    bar.add(new StyledEditorKit.FontSizeAction("16", 16));
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.add(bar, BorderLayout.NORTH);
    this.add(editorPane, BorderLayout.CENTER);
    this.pack();/* www . j  a v a  2 s  . c  om*/
    this.setVisible(true);
}

From source file:Main.java

public void createJEditorPane(Container bg, Dimension size) {
    JEditorPane pane = new JEditorPane();
    pane.setEditable(false);/*from ww w  .  java 2 s. c o  m*/
    HTMLEditorKit editorKit = new HTMLEditorKit();
    pane.setEditorKit(editorKit);
    pane.setSize(size);
    pane.setMinimumSize(size);
    pane.setMaximumSize(size);
    pane.setOpaque(true);
    pane.setText(
            "<b><font face=\"Arial\" size=\"50\" align=\"center\" > Unfortunately when I display this string it is too long and doesn't wrap to new line!</font></b>");
    bg.add(pane, BorderLayout.CENTER);
}

From source file:LoadSync.java

public static void doLoadCommand(JTextComponent textComponent, String filename) {
    FileReader reader = null;//from  w  w  w  . j  a v a2  s .c o m
    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) {
            }
        }
    }
}

From source file:HTML.java

/**
 * Utility method to convert HTML to text.
 * @param html The string containing HTML.
 * @return a String containing the derived text .
 *//*from  www  .j  a va2s  . c o m*/
public static final String html2text(String html) {
    EditorKit kit = new HTMLEditorKit();
    Document doc = kit.createDefaultDocument();
    doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
    try {
        Reader reader = new StringReader(html);
        kit.read(reader, doc, 0);
        return doc.getText(0, doc.getLength());
    } catch (Exception e) {

        return "";
    }
}

From source file:groovesquid.GetAdsThread.java

@Override
public void run() {
    AdsResponse adsResponse = gson.fromJson(getFile(getAdsUrl), AdsResponse.class);
    ads = adsResponse.getAds();/*from ww  w. j  av  a  2s  .co m*/
    if (ads.size() > 0) {
        Random randomGenerator = new Random();
        int index = randomGenerator.nextInt(ads.size());

        AdsResponse.Ad ad = ads.get(index);

        HTMLEditorKit kit = new HTMLEditorKit();
        adPane.setEditorKit(kit);

        StyleSheet styleSheet = kit.getStyleSheet();
        styleSheet.addRule("body { width: 160px; margin: 0; padding: 10px 0 0 0; }");
        //styleSheet.addRule("div { width: 160px; height:600px; position:absolute; top:50%; margin-top:-300px; }");
        String result = "<html><body><div><a href=\"" + ad.getUrl() + "\"><img src=\"" + ad.getImage()
                + "\" alt=\"" + ad.getTitle() + "\" border=\"0\"/></a></div></body></html>";
        Document doc = kit.createDefaultDocument();
        adPane.setDocument(doc);
        adPane.setText(result);

        System.out.println(result);
    }

}

From source file:com.mirth.connect.client.ui.ExportChannelLibrariesDialog.java

private void initComponents(Channel channel) {
    label1 = new JLabel("   The following code template libraries are linked to this channel:");
    label1.setIcon(UIManager.getIcon("OptionPane.questionIcon"));

    librariesTextPane = new JTextPane();
    librariesTextPane.setContentType("text/html");
    HTMLEditorKit editorKit = new HTMLEditorKit();
    StyleSheet styleSheet = editorKit.getStyleSheet();
    styleSheet.addRule(".export-channel-libraries-dialog {font-family:\"Tahoma\";font-size:11;text-align:top}");
    librariesTextPane.setEditorKit(editorKit);
    librariesTextPane.setEditable(false);
    librariesTextPane.setBackground(getBackground());
    librariesTextPane.setBorder(null);/*www .j  a  v  a 2  s.co m*/

    StringBuilder librariesText = new StringBuilder("<html><ul class=\"export-channel-libraries-dialog\">");
    for (CodeTemplateLibrary library : PlatformUI.MIRTH_FRAME.codeTemplatePanel.getCachedCodeTemplateLibraries()
            .values()) {
        if (library.getEnabledChannelIds().contains(channel.getId()) || (library.isIncludeNewChannels()
                && !library.getDisabledChannelIds().contains(channel.getId()))) {
            librariesText.append("<li>").append(StringEscapeUtils.escapeHtml4(library.getName()))
                    .append("</li>");
        }
    }
    librariesText.append("</ul></html>");
    librariesTextPane.setText(librariesText.toString());
    librariesTextPane.setCaretPosition(0);

    librariesScrollPane = new JScrollPane(librariesTextPane);

    label2 = new JLabel("Do you wish to include these libraries in the channel export?");

    alwaysChooseCheckBox = new JCheckBox(
            "Always choose this option by default in the future (may be changed in the Administrator settings)");

    yesButton = new JButton("Yes");
    yesButton.setMnemonic('Y');
    yesButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            result = JOptionPane.YES_OPTION;
            if (alwaysChooseCheckBox.isSelected()) {
                Preferences.userNodeForPackage(Mirth.class).putBoolean("exportChannelCodeTemplateLibraries",
                        true);
            }
            dispose();
        }
    });

    noButton = new JButton("No");
    noButton.setMnemonic('N');
    noButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            result = JOptionPane.NO_OPTION;
            if (alwaysChooseCheckBox.isSelected()) {
                Preferences.userNodeForPackage(Mirth.class).putBoolean("exportChannelCodeTemplateLibraries",
                        false);
            }
            dispose();
        }
    });

    cancelButton = new JButton("Cancel");
    cancelButton.setMnemonic('C');
    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            result = JOptionPane.CANCEL_OPTION;
            dispose();
        }
    });
}