1

我正在尝试使用 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);
        }
    });

关于如何让它发挥作用的任何建议?还是有更好的方法?

谢谢

4

1 回答 1

2

getSelectedText()只返回一个包含所选文本的普通字符串;您不能使用它来修改文本的属性。

我将首先使用SimpleAttributeSetStyleConstants生成颜色属性,然后将其应用于文本的选定部分:

SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, c);
textPane.setCharacterAttributes(attr, false);
于 2010-11-20T19:33:37.710 回答