You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Swing中为JEditorPane选中内容包裹bold标签实现加粗的问题

解决方案

方案1:使用HTMLEditorKit内置加粗动作(推荐)

HTMLEditorKit已经封装了符合常规文字编辑器逻辑的加粗功能,无需自行处理选中范围、标签插入逻辑,还自带加粗状态切换(已加粗的选中内容点击按钮会取消加粗),直接调用即可:

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == boldButton_) {
        int selectStart = editArea_.getSelectionStart();
        int selectEnd = editArea_.getSelectionEnd();
        // 仅在有选中文本时执行
        if (selectStart != selectEnd) {
            // 直接调用内置加粗动作
            new HTMLEditorKit.BoldAction().actionPerformed(
                new ActionEvent(editArea_, ActionEvent.ACTION_PERFORMED, null)
            );
        }
        editArea_.requestFocusInWindow();
    }
}

方案2:手动实现标签插入逻辑

如果需要自定义加粗逻辑,可以按以下思路修改原有代码:
你之前的错误在于调用insertAfterStart是往段落开头插入内容,正确逻辑是先删除原选中内容,再插入包裹了<b>标签的选中文本:

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == boldButton_) {
        HTMLDocument doc = (HTMLDocument) editArea_.getDocument();
        int selectStart = editArea_.getSelectionStart();
        int selectEnd = editArea_.getSelectionEnd();
        if (selectStart != selectEnd) {
            try {
                // 获取选中的纯文本
                String selectedText = editArea_.getSelectedText();
                // 删除原选中内容
                doc.remove(selectStart, selectEnd - selectStart);
                // 插入带<b>标签的内容,insertHTML会自动处理HTML标签解析
                doc.insertHTML(selectStart, "<b>" + selectedText + "</b>", 0, 0, HTML.Tag.B);
            } catch (BadLocationException | IOException ex) {
                ex.printStackTrace();
            }
        }
        editArea_.requestFocusInWindow();
    }
}

如果需要支持取消加粗,可先通过doc.getCharacterElement(selectStart).getAttributes().getAttribute(StyleConstants.NameAttribute)获取当前选中文本的标签,判断是否为HTML.Tag.B,如果是则替换为不带标签的纯文本即可。

内容的提问来源于stack exchange,提问作者Geoff L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 04:15:04