Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

string - change specific text color in java

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 of HELLO..same exact thing on how to change the WORLD in to bold

i wanted to set these string in to a jtextarea but all i can find is something like this

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

these makes the whole sentence into red instead of only making WORLD into red?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...