Change text color in java

I am wondering how can I change a certain color of text in a sentence?

Says HELLO WORLD ... I wanted to change WORLD to red without changing the font color of HELLO. The exact same thing about how to change WORLD in to bold

I wanted to set this line in jtextarea, but all I can find is something like this

JTextArea textbox = new JTextArea("hello world");
textbox.setForeground(Color.red)

does this make the whole sentence red, and not just make WORLD red?

+1
source share
1 answer

Oracle . A JTextArea , . , JTextPane, , , HTML.

:

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);
    }
}
+5

All Articles