JEditorPaneHTMLEditorKitParserReplace替换操作

wen java案例 1

本文目录导读:

JEditorPaneHTMLEditorKitParserReplace替换操作

  1. 基本替换操作
  2. 高级HTML解析和替换
  3. 使用HTMLEditorKit进行解析
  4. 完整的替换工具类

我来为您详细解释如何使用JEditorPane和HTMLEditorKit进行HTML解析和替换操作。

基本替换操作

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.io.*;
public class HTMLReplaceExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("HTML Replace Example");
        JEditorPane editorPane = new JEditorPane();
        editorPane.setContentType("text/html");
        editorPane.setEditable(true);
        // 设置HTML内容
        String htmlContent = "<html><body>" +
            "<h1>原始标题</h1>" +
            "<p>这是一段文本内容</p>" +
            "<p>包含需要替换的文本</p>" +
            "<a href='http://example.com'>链接文本</a>" +
            "</body></html>";
        editorPane.setText(htmlContent);
        // 创建按钮进行替换
        JButton replaceButton = new JButton("替换文本");
        replaceButton.addActionListener(e -> {
            // 执行替换操作
            replaceInHTMLEditor(editorPane, "替换", "已替换");
        });
        frame.add(new JScrollPane(editorPane));
        frame.add(replaceButton, java.awt.BorderLayout.SOUTH);
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

高级HTML解析和替换

import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
import java.util.*;
public class AdvancedHTMLReplace {
    /**
     * 替换HTML中的指定文本
     */
    public static void replaceInHTMLEditor(JEditorPane editor, 
                                          String oldText, 
                                          String newText) {
        try {
            Document doc = editor.getDocument();
            String content = doc.getText(0, doc.getLength());
            // 替换文本
            content = content.replaceAll(
                Pattern.quote(oldText), 
                Matcher.quoteReplacement(newText)
            );
            // 更新文档
            editor.setText(content);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
    /**
     * 使用正则表达式替换HTML内容
     */
    public static void replaceWithRegex(JEditorPane editor, 
                                       String regex, 
                                       String replacement) {
        try {
            Document doc = editor.getDocument();
            String content = doc.getText(0, doc.getLength());
            // 使用正则替换
            content = content.replaceAll(regex, replacement);
            // 更新文档
            editor.setText(content);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
    /**
     * 替换特定HTML标签内的文本
     */
    public static void replaceInTag(JEditorPane editor, 
                                   String tag, 
                                   String oldText, 
                                   String newText) {
        try {
            Document doc = editor.getDocument();
            String content = doc.getText(0, doc.getLength());
            // 使用正则匹配特定标签内的内容
            String regex = "(<" + tag + "[^>]*>)(.*?)(" + Pattern.quote(oldText) + ")(.*?</" + tag + ">)";
            String replacement = "$1$2" + Matcher.quoteReplacement(newText) + "$4";
            content = content.replaceAll(regex, replacement);
            // 更新文档
            editor.setText(content);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
    /**
     * 批量替换多个文本
     */
    public static void batchReplace(JEditorPane editor, 
                                   Map<String, String> replacements) {
        try {
            Document doc = editor.getDocument();
            String content = doc.getText(0, doc.getLength());
            for (Map.Entry<String, String> entry : replacements.entrySet()) {
                content = content.replaceAll(
                    Pattern.quote(entry.getKey()), 
                    Matcher.quoteReplacement(entry.getValue())
                );
            }
            // 更新文档
            editor.setText(content);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
}

使用HTMLEditorKit进行解析

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
public class HTMLEditorKitParserExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("HTMLEditorKit Parser Example");
        JEditorPane editorPane = new JEditorPane();
        // 设置HTML编辑器套件
        HTMLEditorKit kit = new HTMLEditorKit();
        editorPane.setEditorKit(kit);
        editorPane.setEditable(true);
        // 设置初始HTML内容
        String html = "<html><body>" +
            "<h1>标题</h1>" +
            "<p>段落文本 <b>加粗文本</b> 普通文本</p>" +
            "<ul><li>列表项1</li><li>列表项2</li></ul>" +
            "</body></html>";
        editorPane.setText(html);
        JButton parseButton = new JButton("解析和替换");
        parseButton.addActionListener(e -> {
            // 使用HTMLEditorKit解析
            HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
            HTMLDocument.Iterator iterator = doc.getIterator(
                HTML.Tag.CONTENT
            );
            while (iterator.isValid()) {
                try {
                    int start = iterator.getStartOffset();
                    int end = iterator.getEndOffset();
                    String text = doc.getText(start, end - start);
                    // 执行替换逻辑
                    if (text.contains("原始文本")) {
                        // 替换文本
                        doc.replace(start, end - start, "新文本", null);
                    }
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }
                iterator.next();
            }
        });
        JPanel panel = new JPanel();
        panel.add(parseButton);
        frame.add(new JScrollPane(editorPane));
        frame.add(panel, java.awt.BorderLayout.SOUTH);
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

完整的替换工具类

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.util.regex.*;
public class HTMLEditorReplaceUtil {
    /**
     * 简单文本替换(替换纯文本内容,不涉及HTML标签)
     */
    public static void simpleTextReplace(JEditorPane editor, 
                                        String oldText, 
                                        String newText) {
        try {
            HTMLDocument doc = (HTMLDocument) editor.getDocument();
            String content = getTextContent(doc);
            // 替换文本
            content = content.replace(oldText, newText);
            // 重新设置内容
            editor.setText(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 智能替换(保留HTML结构)
     */
    public static void smartReplace(JEditorPane editor, 
                                   String oldText, 
                                   String newText) {
        try {
            HTMLDocument doc = (HTMLDocument) editor.getDocument();
            String html = getHTMLContent(doc);
            // 仅替换不在标签内的文本
            html = replaceTextInContent(html, oldText, newText);
            // 更新编辑器内容
            editor.setText(html);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 替换指定标签内的文本
     */
    public static void replaceInSpecifiedTag(JEditorPane editor, 
                                            String tagName, 
                                            String oldText, 
                                            String newText) {
        try {
            HTMLDocument doc = (HTMLDocument) editor.getDocument();
            String html = getHTMLContent(doc);
            // 匹配指定标签内的内容
            String pattern = "<" + tagName + "[^>]*>([^<]*" + 
                           Pattern.quote(oldText) + "[^<]*)</" + tagName + ">";
            html = html.replaceAll(pattern, 
                    "<" + tagName + ">$1</" + tagName + ">".replace(oldText, newText));
            editor.setText(html);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取文本内容(不含HTML标签)
     */
    private static String getTextContent(HTMLDocument doc) throws BadLocationException {
        StringBuilder sb = new StringBuilder();
        ElementIterator iterator = new ElementIterator(doc);
        Element element;
        while ((element = iterator.next()) != null) {
            if (element.getName().equals("content")) {
                int start = element.getStartOffset();
                int end = element.getEndOffset();
                sb.append(doc.getText(start, end - start));
            }
        }
        return sb.toString();
    }
    /**
     * 获取完整的HTML内容
     */
    private static String getHTMLContent(HTMLDocument doc) throws BadLocationException {
        return doc.getText(0, doc.getLength());
    }
    /**
     * 替换文本内容(保留HTML标签)
     */
    private static String replaceTextInContent(String html, 
                                              String oldText, 
                                              String newText) {
        StringBuilder result = new StringBuilder();
        boolean inTag = false;
        StringBuilder currentText = new StringBuilder();
        for (int i = 0; i < html.length(); i++) {
            char c = html.charAt(i);
            if (c == '<') {
                // 处理之前累积的文本
                if (currentText.length() > 0) {
                    String processed = currentText.toString()
                        .replace(oldText, newText);
                    result.append(processed);
                    currentText = new StringBuilder();
                }
                inTag = true;
                result.append(c);
            } else if (c == '>') {
                inTag = false;
                result.append(c);
            } else if (!inTag) {
                currentText.append(c);
            } else {
                result.append(c);
            }
        }
        // 处理最后剩余的文本
        if (currentText.length() > 0) {
            result.append(currentText.toString().replace(oldText, newText));
        }
        return result.toString();
    }
    /**
     * 使用示例
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame("HTML Replace Utility");
        JEditorPane editorPane = new JEditorPane();
        editorPane.setContentType("text/html");
        // 设置示例HTML
        String html = "<html><body>" +
            "<h1>Hello World</h1>" +
            "<p>This is a <b>Hello</b> example</p>" +
            "<p>Another Hello text</p>" +
            "</body></html>";
        editorPane.setText(html);
        // 创建各种替换按钮
        JPanel buttonPanel = new JPanel();
        JButton simpleReplace = new JButton("简单替换");
        simpleReplace.addActionListener(e -> 
            simpleTextReplace(editorPane, "Hello", "Hi")
        );
        JButton smartReplace = new JButton("智能替换");
        smartReplace.addActionListener(e -> 
            smartReplace(editorPane, "Hello", "Hi")
        );
        JButton replaceInTag = new JButton("替换在p标签内");
        replaceInTag.addActionListener(e -> 
            replaceInSpecifiedTag(editorPane, "p", "Hello", "Hi")
        );
        buttonPanel.add(simpleReplace);
        buttonPanel.add(smartReplace);
        buttonPanel.add(replaceInTag);
        frame.add(new JScrollPane(editorPane));
        frame.add(buttonPanel, java.awt.BorderLayout.SOUTH);
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
  1. 直接替换:使用 editorPane.setText() 重新设置整个HTML内容
  2. 保留结构:使用正则表达式匹配非标签内的文本进行替换
  3. 解析替换:使用 HTMLDocumentElementIterator 遍历元素进行替换
  4. 性能考虑:对于大型文档,建议使用 HTMLDocument 的迭代器方法

这些方法可以满足大多数HTML内容替换的需求,根据具体场景选择合适的替换策略。

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