我正在尝试使用 JTextPane 制作文本编辑器,但在设置所选文本颜色时遇到问题。这是最好的方案(但显然不起作用):
JMenuItem button = new JMenuItem("Set Color");
toolbar.add(button);
button.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(frame,"Choose a color", getBackground());
textPane.getSelectedText().StyledEditorKit.ForegroundAction("color",c);
}
});
关于如何让它发挥作用有什么建议吗?或者更好的方法?
谢谢
最佳答案
getSelectedText()
仅返回包含所选文本的普通字符串;您不能使用它来修改文本的属性。
我将从使用 SimpleAttributeSet
开始和 StyleConstants
生成颜色属性,然后将其应用到文本的选定部分:
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, c);
textPane.setCharacterAttributes(attr, false);
关于java - 使用 JColorChooser 设置文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4234508/