I am developing a simple WYSIWYG RTF editor in Java and have a small issue. I need to be able to synchronize the style selection toggle buttons (such as bold, italic, underlined) to the users text selection. For example, if the current text selection is plain, the bold, italic and underlined toggle buttons are not selected, but when the user selects some text that is bold and underlined, the bold and underlined toggle buttons are selected.
Now i am fairly sure that JTextPane.getInputAttributes()
gets me the selection attributes I want but there is an issue with listening for caret update events. The issue is that caret listener attached to the JTextPane
seems to be called AFTER the input attribute change occurs. So the selection is always one step behind. That is, i must select the text twice before the toggle buttons are updated!
The important code here is:
textPane.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
syncAttributesWithUI(textPane.getInputAttributes());
}
});
And:
private void syncAttributesWithUI(AttributeSet attributes) {
boldButton.setSelected(StyleConstants.isBold(attributes));
italicButton.setSelected(StyleConstants.isItalic(attributes));
underlineButton.setSelected(StyleConstants.isUnderline(attributes));
}
Thanks in advance!