[英]JTextPane - how to style selected text
我正在寻找最简单的方法来控制所选文本中的JTextPane(其内部文本)字体颜色和字体大小。
我知道我必须看看StyledDocument但它的片段显示JMenu动作监听器技巧但不是JButton :(
我找不到可以显示如何通过单击JButton(actionPerformed(...)方法)等来更改所选文本样式的代码片段:(
我的意思是朝这个方向发展
我找不到这种片段,所以我需要你的建议。
任何有用的评论表示赞赏
在适用的jbutton的actionPerformed方法中,你可以运行它。 (根据需要修改。)
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);
但它的片段显示了JMenu动作监听器技巧但不是JButton
您可以将动作添加到JButton以及JMenu。 例如:
Jbutton button = new JButton( new StyledEditorKit.FontSizeAction("16", 16) );
如果要将多个属性同时应用于一段文本,则可以使用样式。
根据@scartag的答案和关于API的评论(来自@kleopatra),我找到了另一种方法。
StyleContext context = new StyleContext();
Style style = context.addStyle("mystyle", null);
style.addAttribute(StyleConstants.FontSize, new Integer(16));;
jTextPane.setCharacterAttributes(style , true);
方法setCharacterAttributes(style, replace)
更改所选文本的样式,因此您无需将其删除并再次使用新样式添加。 而且,boolean replace表示样式是否替换旧样式( true
)或者是否添加到旧样式( false
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.