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