views:

95

answers:

1

I'm trying to create a simple WYSIWYG editor that will allow users to select text and bold/underline/italicise it. Currently the user can select text, right-click it and select bold from a popup menu, which ends up applying the bold style to the selected text like so:

this.getStyledDocument().setCharacterAttributes(this.getSelectionStart(), this.getSelectionEnd()-this.getSelectionStart(), boldStyle, false);

The bold style is set up like so:

boldStyle = this.addStyle("Bold", null);
StyleConstants.setBold(boldStyle, true);

What I would like to know, is if it is possible to get the style for the currently selected text, so that if a user attempts to "bold" some text that is already bold, I can detect this and write code to un-bold this text instead of simply applying the bold style to it again?

Something like:

if(!this.getStyledDocument().getStyleForSelection(this.getSelectionStart(), this.getSelectionEnd()-this.getSelectionStart()).isBold()){
//do bold
}
else{
//un-bold
}

Would be a dream come true, but I have no hope for this. What I'm realistically hoping for is to either be told I'm doing it wrong and be shown "the way", or to be pointed in the direction of a round-a-bout method of achieving this.

Thank you very much for your time.

+4  A: 

The easiest way to do this is via the StyledEditorKit:

JTextPane text = new JTextPane();
JButton button = new JButton("bold");
button.addActionListener(new StyledEditorKit.BoldAction());

JFrame frame = new JFrame("Styled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(text, BorderLayout.CENTER);
frame.setSize(600, 400);
frame.setVisible(true);
McDowell
+1: you might want to check out the other options in StyledEditorKit provides as well. It might come in handy for other aspects of your WYSIWYG editor
akf
Thank you very much for this. Again, the proper solution was so simple! I deleted the addActionCommand and addActionListener from my popup menu items and used "bold.addActionListener(new StyledEditorKit.BoldAction());", which worked perfectly. Thanks again!
Michael Robinson