Java Tutorial/Swing/HTML Document
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.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.parser.ParserDelegator; public class MainClass
public static void main(String args[]) throws Exception < URL url = new URL("http://www.google.ru"); 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); for (HTMLDocument.Iterator iterator = htmlDoc.getIterator(HTML.Tag.A); iterator.isValid(); iterator .next()) < AttributeSet attributes = iterator.getAttributes(); String srcString = (String) attributes.getAttribute(HTML.Attribute.HREF); System.out.print(srcString); int startOffset = iterator.getStartOffset(); int endOffset = iterator.getEndOffset(); int length = endOffset - startOffset; String text = htmlDoc.getText(startOffset, length); System.out.println(" � " + text); >>
url?sa=p&pref=ig&pval=3&q=http://www.google.ca/ig%3Fhl%3Den&usg=__o-KrRDBI3nbRElKzYEMqfOl3_t0= � Personalize this page https://www.google.ru/accounts/Login?continue=http://www.google.ca/&hl=en � Sign in http://images.google.ca/imghp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wi � Images http://groups.google.ca/grphp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wg � Groups http://news.google.ca/nwshp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wn � News /maps?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wl � Maps http://scholar.google.ru/schhp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=ws � Scholar /intl/en/options/ � more�� /advanced_search?hl=en � Advanced Search /preferences?hl=en � Preferences /language_tools?hl=en � Language Tools
Finding out interested element
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.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.parser.ParserDelegator; public class MainClass
public static void main(String args[]) throws Exception < URL url = new URL("http://www.google.ru"); 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); for (HTMLDocument.Iterator iterator = htmlDoc.getIterator(HTML.Tag.A); iterator.isValid(); iterator .next()) < AttributeSet attributes = iterator.getAttributes(); String srcString = (String) attributes.getAttribute(HTML.Attribute.HREF); System.out.print(srcString); int startOffset = iterator.getStartOffset(); int endOffset = iterator.getEndOffset(); int length = endOffset - startOffset; String text = htmlDoc.getText(startOffset, length); System.out.println(" � " + text); >>
url?sa=p&pref=ig&pval=3&q=http://www.google.ca/ig%3Fhl%3Den&usg=__o-KrRDBI3nbRElKzYEMqfOl3_t0= � Personalize this page https://www.google.ru/accounts/Login?continue=http://www.google.ca/&hl=en � Sign in http://images.google.ca/imghp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wi � Images http://groups.google.ca/grphp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wg � Groups http://news.google.ca/nwshp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wn � News /maps?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wl � Maps http://scholar.google.ru/schhp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=ws � Scholar /intl/en/options/ � more�� /advanced_search?hl=en � Advanced Search /preferences?hl=en � Preferences /language_tools?hl=en � Language Tools
HTML Tag Constants
HyperlinkListener Example
import java.io.IOException; import java.net.URL; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.Document; class ActivatedHyperlinkListener implements HyperlinkListener
JEditorPane editorPane; public ActivatedHyperlinkListener(JEditorPane editorPane) < this.editorPane = editorPane; >public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) < HyperlinkEvent.EventType type = hyperlinkEvent.getEventType(); final URL url = hyperlinkEvent.getURL(); if (type == HyperlinkEvent.EventType.ENTERED) < System.out.println("URL: " + url); >else if (type == HyperlinkEvent.EventType.ACTIVATED) < System.out.println("Activated"); Document doc = editorPane.getDocument(); try < editorPane.setPage(url); >catch (IOException ioException) < System.out.println("Error following link, Invalid link"); editorPane.setDocument(doc); >> >
> public class EditorPaneSample
public static void main(String args[]) < JFrame frame = new JFrame("EditorPane Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try < JEditorPane editorPane = new JEditorPane("http://www.google.ru"); editorPane.setEditable(false); HyperlinkListener hyperlinkListener = new ActivatedHyperlinkListener(editorPane); editorPane.addHyperlinkListener(hyperlinkListener); JScrollPane scrollPane = new JScrollPane(editorPane); frame.add(scrollPane); > catch (IOException e) < System.err.println("Unable to load: " + e); >frame.setSize(640, 480); frame.setVisible(true); >
Iterating Across HTML Documents for Links
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.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.parser.ParserDelegator; public class MainClass
public static void main(String args[]) throws Exception < URL url = new URL("http://www.google.ru"); 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); for (HTMLDocument.Iterator iterator = htmlDoc.getIterator(HTML.Tag.A); iterator.isValid(); iterator .next()) < AttributeSet attributes = iterator.getAttributes(); String srcString = (String) attributes.getAttribute(HTML.Attribute.HREF); System.out.print(srcString); int startOffset = iterator.getStartOffset(); int endOffset = iterator.getEndOffset(); int length = endOffset - startOffset; String text = htmlDoc.getText(startOffset, length); System.out.println(" - " + text); >>
url?sa=p&pref=ig&pval=3&q=http://www.google.ca/ig%3Fhl%3Den&usg=__o-KrRDBI3nbRElKzYEMqfOl3_t0= � Personalize this page https://www.google.ru/accounts/Login?continue=http://www.google.ca/&hl=en � Sign in http://images.google.ca/imghp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wi � Images http://groups.google.ca/grphp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wg � Groups http://news.google.ca/nwshp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wn � News /maps?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=wl � Maps http://scholar.google.ru/schhp?ie=ISO-8859-1&oe=ISO-8859-1&hl=en&tab=ws � Scholar /intl/en/options/ � more�� /advanced_search?hl=en � Advanced Search /preferences?hl=en � Preferences /language_tools?hl=en � Language Tools
Look for specific tag types, such as HTML.Tag.H1, HTML.Tag.H2
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 MainClass
public static void main(String args[]) throws Exception < URL url = new URL("http://www.google.ru"); 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); 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)); >> > > >
How to Use HTML in Swing Components
Many Swing components display a text string as part of their GUI. By default, a component’s text is displayed in a single font and color, all on one line. You can determine the font and color of a component’s text by invoking the component’s setFont and setForeground methods, respectively. For example, the following code creates a label and then sets its font and color:
label = new JLabel("A label"); label.setFont(new Font("Serif", Font.PLAIN, 14)); label.setForeground(new Color(0xffffdd));
If you want to mix fonts or colors within the text, or if you want formatting such as multiple lines, you can use HTML. HTML formatting can be used in all Swing buttons, menu items, labels, tool tips, and tabbed panes, as well as in components such as trees and tables that use labels to render text.
To specify that a component’s text has HTML formatting, just put the tag at the beginning of the text, then use any valid HTML in the remainder. Here is an example of using HTML in a button’s text:
button = new JButton("Two
lines");
Here is the resulting button.
An Example: HtmlDemo
An application called HtmlDemo lets you play with HTML formatting by setting the text on a label. You can find the entire code for this program in HtmlDemo.java . Here is a picture of the HtmlDemo example.
Try This:
- Click the Launch button to run HtmlDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
- Edit the HTML formatting in the text area at the left and click the «Change the label» button. The label at the right shows the result.
- Remove the tag from the text area on the left. The label’s text is no longer parsed as HTML.
Example 2: ButtonHtmlDemo
Let us look at another example that uses HTML. ButtonHtmlDemo adds font, color, and other text formatting to three buttons. You can find the entire code for this program in ButtonHtmlDemo.java . Here is a picture of the ButtonHtmlDemo example.
Click the Launch button to run ButtonHtmlDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
The left and right buttons have multiple lines and text styles and are implemented using HTML. The middle button, on the other hand, uses just one line, font, and color, so it does not require HTML. Here is the code that specifies the text formatting for these three buttons:
b1 = new JButton("Disable
" + "middle button", leftButtonIcon); Font font = b1.getFont().deriveFont(Font.PLAIN); b1.setFont(font); . b2 = new JButton("middle button", middleButtonIcon); b2.setFont(font); b2.setForeground(new Color(0xffffdd)); . b3 = new JButton("Enable
" + "middle button", rightButtonIcon); b3.setFont(font);
Note that we have to use a tag to cause the mnemonic characters «D» and «E» to be underlined in the buttons that use HTML. Note also that when a button is disabled, its HTML text unfortunately remains black, instead of becoming gray. (Refer to bug #4783068 to see if this situation changes.)
This section discussed how to use HTML in ordinary, non-text components. For information on components whose primary purpose is formatting text, see Using Text Components.
If you are programming in JavaFX, see HTML Editor.