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



我使用Java Swing,我有一个JEditorPane的内容类型为"text/html">

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

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

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

我不知道如何做到这一点。这是我到目前为止的代码,这是粗体按钮上的事件处理程序。我能做的最好的事情就是在选定文本的段落开头插入一些用粗体包裹的文本,但我想要的是在选定文本周围只插入粗体标签,所以效果是像在任何文字处理程序中一样将所选内容加粗。

提前感谢。

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();
}
}

最新更新