Java Swing JEditorPane 在选择周围插入粗体标记

Java Swing JEditorPane insert bold tags around selection

我正在使用 Java Swing,我有一个内容类型为“text/html”的 JEditorPane“

目前我在编辑器窗格中的唯一内容是:

<html><p>This is a short sentence</p></html>

我想要的是用户能够使用鼠标 select 该句子的任何部分。当他们点击按钮 (boldButton_) 时,它需要将 selection 中的文本加粗。

我不确定如何完成此操作。这是我到目前为止的代码,它是粗体按钮上的事件处理程序。我能做的最好的事情是在包含 selected 文本的段落开头插入一些用粗体包裹的文本,但我想要的是仅在 selected 文本周围插入粗体标记,所以效果是像在任何文字处理器中一样加粗 selection。

提前致谢。

JEditorPane editArea_;


public void actionPerformed(ActionEvent e) {

    // bold button
    if (e.getSource() == boldButton_) {
        
        
        HTMLDocument doc = (HTMLDocument) editArea_.getDocument();
        HTMLEditorKit ekit = (HTMLEditorKit) editArea_.getEditorKit();
        
        int selectStart = editArea_.getSelectionStart();
        int selectEnd = editArea_.getSelectionEnd();
        Element startElem = doc.getParagraphElement(selectStart);
        Element endElem = doc.getParagraphElement(selectEnd);
                        
        // for now only bold if some text has been selected with the mouse
        if (selectStart != selectEnd) {
            
            // 1. text is selected
            // toggle bold tags around the text
            try {
                doc.insertAfterStart(startElem, "<b>WTF</b>");
            } catch (BadLocationException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
                
            
        } 
        editArea_.requestFocusInWindow();

    }
}

我不确定,但你可以试试这个代码。

 // toggle bold tags around the text
 String txt = doc.getSelectedText();
 if (selectStart != selectEnd) {
    try {
        // doc.insertAfterStart(startElem, "<b>WTF</b>");
        doc.remove(selectStart, selectEnd-selectStart);
        ekit.insertHTML((HTMLDocument) doc.getDocument(), selectStart, "<b>"+txt+"</b>", 0, 0, HTML.Tag.B);
    } catch (BadLocationException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
 }