Search code examples
javaswingjtextpane

How to check if the insertion point is on a bold or normal text


I am making a text application where I can change the text to bold (I will add more in the future).

I put the bold option in a JMenu as a JCheckBox.

I want this checkbox to get selected or deselected depending on whether the insertion point (the blinking line) is on a bold or normal text. Just like it is in Microsoft Word.

The application


Solution

  • Quick answer from my phone: You need to add a CaretListener to the document. When triggered, you will detect the character style with StyledDocument.getCharacterAttributes. To get the bold attribute, you check it with StyleConstants.isBold. Be careful to not trigger your bold action while setting the check box state.