Reputation: 5
I have a JTextField where I enter black characters. I want the color of one letter in the text field to change to red under a certain condition. If this condition is not met, then the color changes back to black.
I tryed to use a textField.setForegroung(new Color(237, 42, 42)
, but it changes a color of all text. I need to change a color of one character.
Upvotes: 1
Views: 125
Reputation: 711
You can't define the color of individual chars in a JTextField. You need to use a JTextPane (or JEditorPane). With these components, you can use DefaultStyledDocument to define your text styles.
Here's an example:
public class MyApplication extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyApplication app = new MyApplication();
app.setVisible(true);
}
});
}
private MyApplication() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
StyleContext sc = new StyleContext();
DefaultStyledDocument doc = new DefaultStyledDocument(sc);
JTextPane textPane = new JTextPane(doc);
textPane.setText("This is some colored text.");
// Create a new style
Style coloredCharStyle = sc.addStyle("ColorChars", null);
coloredCharStyle.addAttribute(StyleConstants.Foreground, Color.red);
// Define where the style should be applied
doc.setCharacterAttributes(13,7,coloredCharStyle,false);
// Add textPane to JFrame
add(textPane, BorderLayout.CENTER);
setVisible(true);
}
}
Upvotes: 2