Reputation: 3704
I am looking for the most simple way to control JTextPane (its inner text) font color and font size within selected text only.
I know I must look at StyledDocument but its snippets show the JMenu action listener tricks but not JButton :(
I couldn't find code snippets which could show how to change selected text style by JButton clicked (the actionPerformed(...) method) etc :(
I mean something in this direction
I couldn't find this kind of snippets so I need your advice.
Any useful comment is appreciated
Upvotes: 1
Views: 3533
Reputation: 11016
Based on @scartag answer and the comment about the API (from @kleopatra), I have found another way to do it.
StyleContext context = new StyleContext();
Style style = context.addStyle("mystyle", null);
style.addAttribute(StyleConstants.FontSize, new Integer(16));;
jTextPane.setCharacterAttributes(style , true);
The method setCharacterAttributes(style, replace)
changes the style of the selected text so you don't need to remove it and add again with a new style. And more, the boolean replace indicates if the style replaces the old style (true
) or if is added to the old style (false
).
Upvotes: 0
Reputation: 324118
but its snippets show the JMenu action listener tricks but not JButton
You can add an Action to a JButton as well as well as a JMenu. For example:
Jbutton button = new JButton( new StyledEditorKit.FontSizeAction("16", 16) );
You would use Styles when you want to apply multiple properies at one time to a piece of text.
Upvotes: 2
Reputation: 17680
In your actionPerformed method of the applicable jbutton you could run this. (modify as needed.)
String text = jTextPane.getSelectedText();
int cursorPosition = jTextPane.getCaretPosition();
StyleContext context = new StyleContext();
Style style;
jTextPane.replaceSelection("");
style = context.addStyle("mystyle", null);
style.addAttribute(StyleConstants.FontSize, new Integer(16));
jTextPane.getStyledDocument().insertString(cursorPosition - text.length(), text, style);
Upvotes: 2