Archives: HTML

Java – Extract links from HTML page

[code lang=”java”]import java.io.FileReader;
import java.util.ArrayList;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.parser.ParserDelegator;

public class Main {

public final static void main(String[] args) throws Exception {
final ArrayList<String> list = new ArrayList<String>();

ParserDelegator parserDelegator = new ParserDelegator();
ParserCallback parserCallback = new ParserCallback() {
public void handleText(final char[] data, final int pos) {
}

public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) {
if (tag == Tag.A) {
String address = (String) attribute.getAttribute(Attribute.HREF);
list.add(address);
}
}

public void handleEndTag(Tag t, final int pos) {
}

public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) {
}

public void handleComment(final char[] data, final int pos) {
}

public void handleError(final java.lang.String errMsg, final int pos) {
}
};
parserDelegator.parse(new FileReader("a.html"), parserCallback, false);
System.out.println(list);
}

}[/code]


Java Swing – Format JLabel with HTML

[code lang=”java”]import javax.swing.*;
import java.awt.*;

public class HTMLLabel extends JFrame {

public HTMLLabel() {
setTitle("JLabel with HTML");
initComponents();
}

private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));

//
// Create a JLabel object that display a string formatted using HTML.
// 14 font size with red and italic.
//
JLabel label = new JLabel("<html><font size=\"14\" color=\"ff0000\"><i>Hello World</i></font></html>");
container.add(label);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HTMLLabel().setVisible(true);
}
});
}

}[/code]