1

I am following, http://www.java2s.com/Tutorial/Java/0240__Swing/RegexFormatterwithaJFormattedTextField.htm. In the given example, How to change foreground/text color of JFormattedTextField on its input text not obeying the RegEx format of the formatter?

AVA
  • 2,474
  • 2
  • 26
  • 41
  • 1
    It's very difficult because the text field does not support text formatting. You need to implement a custom view (and UI) which supports something like this. But it can takes some days or weeks. – Sergiy Medvynskyy Jun 07 '16 at 06:53

1 Answers1

3

You can change the foreground color of the JFormattedTextField when the user attempts to change focus using an InputVerifier. Starting from this complete example, condition the color in your implementation of shouldYieldFocus().

@Override
public boolean shouldYieldFocus(JComponent input) {
    if (verify(input)) {
        tf.setValue(date);
        tf.setForeground(Color.black);
        return true;
    } else {
        tf.setForeground(Color.red);
        return false;
    }
}

image

To see changes while typing, use a DocumentListener that evaluates DateFormat instances in a similar way.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045