JEditorPaneHTMLEditorKitParserIndent缩进操作

wen java案例 1

我来帮您分析 JEditorPane 与 HTMLEditorKit 的缩进操作相关功能。

JEditorPaneHTMLEditorKitParserIndent缩进操作

JEditorPane 和 HTMLEditorKit 的缩进处理

JEditorPane 配合 HTMLEditorKit 支持 HTML 内容的显示和编辑,包括缩进功能,以下是关键实现方式:

HTML 缩进支持

import javax.swing.*;
import javax.swing.text.html.*;
import java.awt.*;
import java.io.*;
public class HTMLIndentExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("HTML Indent Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        JEditorPane editorPane = new JEditorPane();
        editorPane.setEditorKit(new HTMLEditorKit());
        editorPane.setContentType("text/html");
        // 支持缩进的 HTML 内容
        String htmlContent = "<html><body>" +
            "<h1>缩进示例</h1>" +
            "<div style='margin-left: 20px;'>" +
            "  <p>这是有缩进的段落</p>" +
            "  <ul>" +
            "    <li style='margin-left: 10px;'>列表项 1</li>" +
            "    <li style='margin-left: 20px;'>列表项 2</li>" +
            "  </ul>" +
            "</div>" +
            "</body></html>";
        editorPane.setText(htmlContent);
        editorPane.setEditable(true);
        frame.add(new JScrollPane(editorPane));
        frame.setVisible(true);
    }
}

实现代码缩进操作

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.awt.event.*;
public class IndentActionExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Indent Actions");
        JEditorPane editor = new JEditorPane();
        editor.setEditorKit(new HTMLEditorKit());
        // 添加快捷键缩进操作
        InputMap inputMap = editor.getInputMap(JComponent.WHEN_FOCUSED);
        ActionMap actionMap = editor.getActionMap();
        // 自定义缩进动作
        Action indentAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                insertIndent(editor);
            }
        };
        // Ctrl+I 触发缩进
        KeyStroke keyStroke = KeyStroke.getKeyStroke(
            KeyEvent.VK_I, InputEvent.CTRL_DOWN_MASK);
        inputMap.put(keyStroke, "indent");
        actionMap.put("indent", indentAction);
        frame.add(new JScrollPane(editor));
        frame.setSize(600, 400);
        frame.setVisible(true);
    }
    private static void insertIndent(JEditorPane editor) {
        try {
            Document doc = editor.getDocument();
            int caretPos = editor.getCaretPosition();
            // 插入缩进(4个空格)
            doc.insertString(caretPos, "    ", null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }
}

自定义 HTML 解析器缩进

import javax.swing.text.html.parser.*;
import javax.swing.text.html.*;
import javax.swing.text.*;
import java.util.*;
public class CustomIndentParser extends HTMLDocument.HTMLReader {
    private int indentLevel = 0;
    private StringBuilder output = new StringBuilder();
    public CustomIndentParser(HTMLDocument doc) {
        super(doc);
    }
    @Override
    public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
        // 输出缩进
        output.append(getIndent());
        output.append("<").append(t.toString());
        // 添加属性
        Enumeration<?> names = a.getAttributeNames();
        while (names.hasMoreElements()) {
            Object name = names.nextElement();
            output.append(" ").append(name).append("='")
                  .append(a.getAttribute(name)).append("'");
        }
        output.append(">\n");
        indentLevel++;
    }
    @Override
    public void handleEndTag(HTML.Tag t, int pos) {
        indentLevel--;
        output.append(getIndent());
        output.append("</").append(t.toString()).append(">\n");
    }
    @Override
    public void handleText(char[] data) {
        output.append(getIndent());
        output.append(data).append("\n");
    }
    private String getIndent() {
        StringBuilder indent = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            indent.append("  "); // 每级2个空格
        }
        return indent.toString();
    }
    public String getFormattedOutput() {
        return output.toString();
    }
}

使用 HTMLEditorKit 的缩进属性

import javax.swing.text.html.*;
import javax.swing.text.*;
public class HTMLStyleIndent {
    public static void main(String[] args) {
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
        // 设置默认缩进样式
        StyleSheet styleSheet = doc.getStyleSheet();
        // 为不同元素设置缩进
        styleSheet.addRule("body { " +
            "margin-left: 10px; " +
            "padding-left: 10px; " +
            "}");
        styleSheet.addRule("div { " +
            "margin-left: 20px; " +
            "padding-left: 15px; " +
            "}");
        styleSheet.addRule("ul { " +
            "margin-left: 30px; " +
            "padding-left: 20px; " +
            "}");
        styleSheet.addRule("li { " +
            "text-indent: -5px; " +
            "margin-left: 40px; " +
            "}");
        // 应用样式
        JEditorPane editor = new JEditorPane();
        editor.setEditorKit(kit);
        editor.setDocument(doc);
    }
}

高级缩进控制

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.awt.*;
public class AdvancedIndentControl {
    public static void createIndentedEditor() {
        JEditorPane editor = new JEditorPane();
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        // 设置视图属性
        ViewFactory factory = kit.getViewFactory();
        // 自定义缩进的 HTML 内容
        String html = String.join("\n",
            "<html>",
            "<head>",
            "<style>",
            "  .indent1 { margin-left: 20px; }",
            "  .indent2 { margin-left: 40px; }",
            "  .indent3 { margin-left: 60px; }",
            "  blockquote {",
            "    margin-left: 30px;",
            "    border-left: 3px solid #ccc;",
            "    padding-left: 15px;",
            "  }",
            "</style>",
            "</head>",
            "<body>",
            "<p>普通段落</p>",
            "<p class='indent1'>缩进一级</p>",
            "<p class='indent2'>缩进二级</p>",
            "<blockquote>",
            "  <p>引用内容,自动缩进</p>",
            "  <p>继续引用内容</p>",
            "</blockquote>",
            "</body>",
            "</html>"
        );
        editor.setText(html);
        editor.setEditable(true);
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(editor));
        frame.setSize(600, 400);
        frame.setVisible(true);
    }
}
  1. CSS 样式控制:通过 CSS 的 margin-left、padding-left、text-indent 控制缩进
  2. HTML 元素:blockquote、ul/ol、dl 等标签提供自然缩进
  3. 自定义解析:可以扩展 HTML 解析器实现自定义缩进格式
  4. 缩进操作:通过 Action 实现缩进/取消缩进功能
  5. 样式表:利用 StyleSheet 统一管理缩进样式

这些技术可以灵活控制 JEditorPane 中的 HTML 内容缩进显示。

抱歉,评论功能暂时关闭!