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