【发布时间】:2016-12-03 04:33:06
【问题描述】:
我正在用 Java 编写一个文本编辑器,使用 Swing。我用来输入文本的主要组件是 JTextPane。我知道如何加粗所选文本,但我也想按粗体并格式化新文本。这是我的代码:
static void boldSelection(JTextPane editor, JButton button){
StyledDocument doc = (StyledDocument) editor.getDocument();
int selectionEnd = editor.getSelectionEnd();
int selectionStart = editor.getSelectionStart();
if (selectionStart == selectionEnd) {
return;
}
Element element = doc.getCharacterElement(selectionStart);
AttributeSet as = element.getAttributes();
MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
doc.setCharacterAttributes(selectionStart, editor.getSelectedText().length(), asNew, true);
}
它有效,但我不知道如何更改它,因为我必须将长度传递给 setCharacterAttributes。 要清楚: 这就是我所拥有的: Bolding selected text 这就是我想要做的: Entering bolded text
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
-
您会希望有一个动作侦听器,它会检查您是否处于“粗体”状态,如果是,则将其应用于输入的字符