How to set Color for selected Text in java? [closed]

拟墨画扇 提交于 2019-12-26 09:23:51

问题


Please any one help for set the color for selected text only... I has Create a Simple Text Editor... But, I can't set the color for selected text contents... once ,I has select the color it will affect the whole text area instead of selected area.

Please Help Any One,

Thanks in Advance.

for Example : 

Now I select the Kumar only..So,will select the color for that selected text only..But,my problem is change the color for unselected text also..

How to resolve it???????


回答1:


With what component do you display your text? If it is JTextArea, then it is not possible. You need a component that allows different styles. For example a StyledDocument in a JTextPane. For more information see How to Use Editor Panes and Text Panes




回答2:


You can try the next:

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);

}



来源:https://stackoverflow.com/questions/19450336/how-to-set-color-for-selected-text-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!