1.创建控件
JScrollPane htmlScrollPane = new JScrollPane();
JEditorPane htmlPane = new JEditorPane();
htmlScrollPane.getViewport().add(htmlPane);
htmlPane.setEditable(false);
2.应用HTMLEditorKit到JEditorPane
HTMLEditorKit kit = new HTMLEditorKit();
htmlPane.setEditorKit(kit);
3.为样式表添加样式
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("table {border-collapse: collapse; border: solid #000000; border-width: 1px 0 0 1px;}");
styleSheet.addRule("table caption {font-size: 12px; font-weight: bolder;}");
styleSheet.addRule("table td {white-space: word-wrap; font-size: 10px; height: 10px; border: solid #000000; border-width: 0 1px 1px 0; padding: 2px; text-align: left; vertical-align: center}");
4.为链接添加点击事件
默认JEditorPane对链接的点击是没有反应的,应添加一个监听器
htmlPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
//如果链接被点击
//do something
}
}
};
5.创建文档,并应用到JEditorPane
Document doc = kit.createDefaultDocument();
htmlPane.setDocument(doc);
String html = generateHTML(); //调用其他方法产生html字符串
htmlPane.setText(html);