Search code examples
javaswingvalidationjtextfieldjformattedtextfield

From JTextField to JFormattedTextField


In NetBeans I've created a project with many of JTextField's. Now I understand that I should validate it. Is it possible to "cast" text fields to JFormattedTextField's?


Solution

  • It is possible to "cast" text fields to JFormattedTextField's?

    No it's not. At least not directly. The other way around is possible though, given JFormattedTextField extends from JTextField.

    So I must delete all JTexFields and add Formatted fields ?

    Not necessarily but it's highly recommended. On the other hand you can let the class' variables declared as JTextField and initialize them as JFormattedTextField through custom code:

    Customize code

    Code customizer

    Then you can "safely" downcast them as JFormattedTextField later. However I'd like to emphasize one more time that it sounds like a dirty workaround. Also note you won't be able to change the setText(...) code to setValue(...) which is preferred for formatted text fields.