我正在寻找在所选文本中控制JTextPane(内部文本)字体颜色和字体大小的最简单方法。
我知道我必须看看StyledDocument,但它的片段显示了JMenu动作监听器技巧但不是JButton :(
我找不到可以显示如何通过单击JButton(actionPerformed(...)方法)等来更改所选文本样式的代码段:(
我的意思是朝这个方向发展
我找不到这种片段,所以我需要你的建议。
赞赏任何有用的评论
答案 0 :(得分:2)
在适用的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);
答案 1 :(得分:2)
但它的片段显示了JMenu动作监听器技巧但不显示JButton
您可以将动作添加到JButton以及JMenu。例如:
Jbutton button = new JButton( new StyledEditorKit.FontSizeAction("16", 16) );
当您想要将多个属性同时应用于一段文本时,您可以使用样式。
答案 2 :(得分:0)
根据@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)
会更改所选文本的样式,因此您无需将其删除并再次添加新样式。此外,布尔替换指示样式是否替换旧样式(true
)或是否添加到旧样式(false
)。