[英]JTextPane - how to style selected text
I am looking for the most simple way to control JTextPane (its inner text) font color and font size within selected text only. 我正在寻找最简单的方法来控制所选文本中的JTextPane(其内部文本)字体颜色和字体大小。
I know I must look at StyledDocument but its snippets show the JMenu action listener tricks but not JButton :( 我知道我必须看看StyledDocument但它的片段显示JMenu动作监听器技巧但不是JButton :(
I couldn't find code snippets which could show how to change selected text style by JButton clicked (the actionPerformed(...) method) etc :( 我找不到可以显示如何通过单击JButton(actionPerformed(...)方法)等来更改所选文本样式的代码片段:(
I mean something in this direction 我的意思是朝这个方向发展
I couldn't find this kind of snippets so I need your advice. 我找不到这种片段,所以我需要你的建议。
Any useful comment is appreciated 任何有用的评论表示赞赏
In your actionPerformed method of the applicable jbutton you could run this. 在适用的jbutton的actionPerformed方法中,你可以运行它。 (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);
but its snippets show the JMenu action listener tricks but not JButton
但它的片段显示了JMenu动作监听器技巧但不是JButton
You can add an Action to a JButton as well as well as a JMenu. 您可以将动作添加到JButton以及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. 如果要将多个属性同时应用于一段文本,则可以使用样式。
Based on @scartag answer and the comment about the API (from @kleopatra), I have found another way to do it. 根据@scartag的答案和关于API的评论(来自@kleopatra),我找到了另一种方法。
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. 方法
setCharacterAttributes(style, replace)
更改所选文本的样式,因此您无需将其删除并再次使用新样式添加。 And more, the boolean replace indicates if the style replaces the old style ( true
) or if is added to the old style ( false
). 而且,boolean replace表示样式是否替换旧样式(
true
)或者是否添加到旧样式( false
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.