2015-01-17 18:19:38|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:Java, Swing, 界面设计|来源:唯设编程网
Swing提供了方便的手段进行界面元素的布局,但是在进行复杂样式布局的时候,使用HTML+CSS比直接使用Swing的界面元素进行布局要方便很多,本文介绍在JEditorPane中使用HTML+CSS布局界面的基本方法,并且还介绍了JEditorPane如何响应HTML中的超链接事件。
首先看看本示例实现的效果:

面板的左侧是一个JList列表控件,列出了保存的快照节点,右侧是使用HTML+CSS进行布局得到对应节点的详细内容。本文着重关注JEditorPane显示HTML的方法,其它内容不做详细介绍。
private JEditorPane htmlPane = new JEditorPane(); private HTMLEditorKit kit = new HTMLEditorKit(); private Document htmlDocument = kit.createDefaultDocument(); /** * 超链接监听器 */ private HyperlinkListener listener = null;
定义4个类的成员变量
this.getViewport().add(htmlPane);
/**
* 初始化HTML面板
*/
private void initHtmlPane() {
//
this.initStyle(kit.getStyleSheet());
listener = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == EventType.ACTIVATED) {
// 保存快照
if (e.getDescription().equals("EVT_SAVE")) {
if(SummaryPanel.this.listServer instanceof ModelAccount){
ModelAccount modAccount = (ModelAccount) SummaryPanel.this.listServer;
try {
modAccount.saveSnap();
JOptionPane.showMessageDialog(SummaryPanel.this, "保存快照成功!");
SummaryPanel.this.loadSnapLableList();
} catch (Exception e1) {
JOptionPane.showMessageDialog(SummaryPanel.this, "出错:"+e1.getMessage());
}
}
}
} else {
String styleName = null;
if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
styleName = ".btn:hover";
} else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
styleName = ".btn";
}
if (styleName != null) {
JEditorPane editor = (JEditorPane) e.getSource();
HTMLDocument doc = (HTMLDocument) editor.getDocument();
Style aStyle = kit.getStyleSheet().getStyle(styleName);
int start = e.getSourceElement().getStartOffset();
int end = e.getSourceElement().getEndOffset();
doc.setCharacterAttributes(start, end - start, aStyle,false);
}
}
}
};
//初始化htmlPane
htmlPane.setEditable(false);
htmlPane.setEditorKit(kit);
htmlPane.addHyperlinkListener(listener);
htmlPane.setDocument(htmlDocument);
}