在Swing的JEditorPane控件中实现超级链接的CSS定义

如下一个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的功能,来达到我们的需求。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值