JEditorPane中使用CSS样式显示HTML

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值