JEditorPane中使用CSS樣式顯示HTML

來源:互聯網
上載者:User

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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.