Enri
Enri

Reputation: 25

Writing with bold in Java using Swing

I'm writing a text editor in Java, using Swing. My main component that I use to enter the text is JTextPane. I know how to bold selected text, but I'd also like just to press bold and have new text formatted. Here's my code:

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

It works, but I have no idea how to change it, since I have to pass the length to setCharacterAttributes. To be clear: that's what I have: Bolding selected text and that's what I want to do: Entering bolded text

Upvotes: 0

Views: 453

Answers (1)

camickr
camickr

Reputation: 324118

The EditorKit used by the JTextPane supports a Bold Action along with other common actions the might be used by an editor. So you don't need to write any special code, only create a Swing component to use the Action.

Check out the section from the Swing tutorial on Text Component Features for a working example.

The tutorial example only use menu items but you can also use the Action to create a JButton to add to a JToolBar.

Upvotes: 2

Related Questions