我正在寻找仅在选定文本中控制 JTextPane(其内部文本)字体颜色和字体大小的最简单方法。
我知道我必须看看 StyledDocument 但它的片段显示了 JMenu Action 监听器技巧而不是 JButton :(
我找不到可以显示如何通过单击 JButton(actionPerformed(...) 方法)等来更改 selected text 样式的代码片段 :(
我的意思是这个方向
- A) 我在 JTextPane 中有一个文本让我们说“我的家将变成 borabora,这是……”
- B) 在 JTextPane 中选择文本“borabora”
- C) JButton("size=16") 被点击
- D) 文本“borabora”大小变为 16
我找不到这种片段,所以我需要你的建议。
感谢任何有用的评论
最佳答案
在适用的 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);
关于java - JTextPane - 如何设置所选文本的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7543346/