| 
         
     
     | 
     | 
    
  
    | 
    在Swing的JEditorPane控件中实现超级链接的CSS定义 | 
   
  
     | 
   
  
     | 
   
  
    | 
     作者:未知  来源:月光软件站  加入时间:2005-2-28 月光软件站  | 
   
  
    如下一个HTML文件 <html>     <head>     <style type='text/css'>         A{text-decoration: none; color: #000000; }         A:hover {text-decoration: underline; color: #FF0000; }     </style> </head> <body>         <a href="www.google.com">Google</a><br>         <a href="www.yahoo.com">Yahoo!</a> </body> </html> 在JEditorPane中显示的时候JEditorPane可以正确显示CSS中对A属性的设置,但是当鼠标移上去的时候却不能把A:hover中的定义显示出来。可能是因为JEditorPane只是在显示的时候解析了一下每一个Element的属性,当鼠标事件发生的时候不能动态的修改Element的属性。
  下面来解决这个问题: 1,获取鼠标移入移出事件,用HyperlinkListener可以捕获,要注意的是这个Listener似乎有一个bug,在超级链接在JEditorPane边上的时候,快速移出JEditorPane似乎会没有EXITED事件的发生,这个bug可以通过给JEditorPane加一个鼠标事件解决(这里不详细描述)。     JEditorPane editor;     ......    ......     HyperlinkListener hyperlinkListener = new HyperlinkListener() {       public void hyperlinkUpdate(HyperlinkEvent e) {         if (e.getEventType() == HyperlinkEvent.EventType.ENTERED){           System.out.println("Mouse Entered");         }else if (e.getEventType() == HyperlinkEvent.EventType.EXITED){           System.out.println("Mouse Exited");         }       }     };     editor.addHyperlinkListener(hyperlinkListener);      2,获取CSS中对于A和A:hover的属性定义           HTMLDocument doc = (HTMLDocument)editor.getDocument();           Style aStyle = doc.getStyleSheet().getStyle("a");           Style aHoverStyle = doc.getStyleSheet().getStyle("a:hover");
  3,在鼠标事件中更换Style     JEditorPane editor;     ......    ......     HyperlinkListener hyperlinkListener = new HyperlinkListener() {       public void hyperlinkUpdate(HyperlinkEvent e) {         String styleName = null;         if (e.getEventType() == HyperlinkEvent.EventType.ENTERED){           styleName = "a:hover";         }else if (e.getEventType() == HyperlinkEvent.EventType.EXITED){           styleName = "a";         }         if (styleName != null){           JieEditorPane editor = (JieEditorPane)e.getSource();           HTMLDocument doc = (HTMLDocument)editor.getDocument();           Style aStyle = doc.getStyleSheet().getStyle(styleName);                      int start = e.getSourceElement().getStartOffset();           int end = e.getSourceElement().getEndOffset();           doc.setCharacterAttributes(start,end-start,aStyle,false);         }       }     };     editor.addHyperlinkListener(hyperlinkListener);
    结论:JEditorPane能够支持简单的HTML和CSS(具体支持的标准不清楚),但是提供了良好的接口和API,我们可以通过这些API来增强JEditorPane的功能,来达到我们的需求。 
 
  | 
   
  
     | 
   
  
     相关文章:相关软件:  | 
   
   
      |