使用Swing

时间:2016-12-02 16:32:10

标签: java swing jtextpane bold

我正在用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

0 个答案:

没有答案