change specific text color in java

前端 未结 1 502
梦毁少年i
梦毁少年i 2021-01-24 07:13

i am wondering how can i change a specific text color in a sentence?

lets say HELLO WORLD...i wanted to change the WORLD into red color without altering the font color

相关标签:
1条回答
  • 2021-01-24 08:03

    Have a look at this this from the Oracle documentation on text components. A JTextArea will accept styling, but it will always apply styling across its entire contents. However, if you were to use a JTextPane, you could create any styling you wanted in your text using HTML.

    Code to back up assertion:

    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.html.HTMLEditorKit;
    
    public class StyleTestApp {
        public static void main(final String[] args) {
            final JFrame f = new JFrame("test");
            //f.getContentPane().add(new JTextArea("<html>HELLO <font size=\"3\" face=\"verdana\" color=\"red\">WORLD</font></html>"));
            final JTextPane p = new JTextPane();
            // the HTMLEditorKit is not enabled by default in the JTextPane class.
            p.setEditorKit(new HTMLEditorKit());
            p.setText("<html>HELLO <font size=\"3\" face=\"verdana\" color=\"red\">WORLD</font></html>");
            f.getContentPane().add(p);
            f.pack();
            f.setVisible(true);
        }
    }
    
    0 讨论(0)
提交回复
热议问题