如何在java中为所选文本设置颜色?

时间:2013-10-18 13:01:24

标签: java swing selection jtextarea

请为任何一个帮助设置所选文本的颜色...我有创建一个简单的文本编辑器...但是,我无法设置所选文本内容的颜色...一次,我选择了颜色会影响整个文本区域而不是选定的区域。

请帮助任何人,

先谢谢。

for Example : 

enter image description here enter image description here

现在我只选择Kumar ..所以,只会选择所选文本的颜色。但是,我的问题是改变未选文本的颜色..

如何解决它????????

2 个答案:

答案 0 :(得分:2)

您使用哪个组件显示文字? 如果它是JTextArea,那么它是不可能的。 您需要一个允许不同样式的组件。例如,JTextPane中的StyledDocument。 有关详细信息,请参阅How to Use Editor Panes and Text Panes

答案 1 :(得分:1)

您可以尝试下一个:

public static void main(String[] args) {

    final JFrame frame = new JFrame("Selected Color Example");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    final JTextArea area = new JTextArea("Text for test...", 5, 10);
    frame.add(area, BorderLayout.CENTER);

    JButton button = new JButton("Select Color");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Color color = JColorChooser.showDialog(frame, "Colors",
                    Color.BLUE);
            area.selectAll();
            // area.setSelectedTextColor(color); // color of selected text
            area.setSelectionColor(color); // background of selected text
            area.requestFocusInWindow();
        }
    });
    frame.add(button, BorderLayout.PAGE_END);

    frame.pack();
    frame.setVisible(true);

}

enter image description here