Swing使用JEditorPane加载显示本地的html文件以及支持的CSS样式

前言

主要使用了JEditorPane的setPage方法,本身支持的CSS样式有限,只适用于展示简单粗糙的html内容

正文

效果

java代码

package demo.html;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;

public class JEditorPaneLoadHtmlDemo {

    public static void main(String[] args) throws IOException {
        JFrame frame = new JFrame("一克金代码");
        frame.setLocationRelativeTo(null);
        frame.setSize(500,600);

        JEditorPane editorPane = new JEditorPane();
        editorPane.setLayout(new BorderLayout());
        URL resource = JEditorPaneLoadHtmlDemo.class.getClass().getResource("/demo/html/test.html");
        editorPane.setPage(resource);

        frame.getContentPane().add(editorPane);
        frame.setVisible(true);
    }


}

html文件代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>Title</h1>
<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item1</li>
</ul>

</body>
</html>

JEditorPane并不支持所有的css样式

根据javax.swing.text.html.CSS.java中的说明
支持的CSS
* <ul><li>font-family
 *   <li>font-style
 *   <li>font-size (supports relative units)
 *   <li>font-weight
 *   <li>font
 *   <li>color
 *   <li>background-color (with the exception of transparent)
 *   <li>background-image
 *   <li>background-repeat
 *   <li>background-position
 *   <li>background
 *   <li>text-decoration (with the exception of blink and overline)
 *   <li>vertical-align (only sup and super)
 *   <li>text-align (justify is treated as center)
 *   <li>margin-top
 *   <li>margin-right
 *   <li>margin-bottom
 *   <li>margin-left
 *   <li>margin
 *   <li>padding-top
 *   <li>padding-right
 *   <li>padding-bottom
 *   <li>padding-left
 *   <li>padding
 *   <li>border-top-style
 *   <li>border-right-style
 *   <li>border-bottom-style
 *   <li>border-left-style
 *   <li>border-style (only supports inset, outset and none)
 *   <li>border-top-color
 *   <li>border-right-color
 *   <li>border-bottom-color
 *   <li>border-left-color
 *   <li>border-color
 *   <li>list-style-image
 *   <li>list-style-type
 *   <li>list-style-position
 * </ul>

列举但不支持的

列举了并不支持的
 * <ul><li>font-variant
 *   <li>background-attachment (background always treated as scroll)
 *   <li>word-spacing
 *   <li>letter-spacing
 *   <li>text-indent
 *   <li>text-transform
 *   <li>line-height
 *   <li>border-top-width (this is used to indicate if a border should be used)
 *   <li>border-right-width
 *   <li>border-bottom-width
 *   <li>border-left-width
 *   <li>border-width
 *   <li>border-top
 *   <li>border-right
 *   <li>border-bottom
 *   <li>border-left
 *   <li>border
 *   <li>width
 *   <li>height
 *   <li>float
 *   <li>clear
 *   <li>display
 *   <li>white-space
 *   <li>list-style
 * </ul>

其他的CSS就更不支持了。

至此Swing使用JEditorPane加载显示本地的html文件以及支持的CSS样式内容完成。

发布了25 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/scc95599/article/details/100773743