Search code examples
javaswingjtextfieldjformattedtextfield

Is there a way to put a colon in a jtextfield so it can't be removed?


I want a user to input time, so like 12:00, but I need to figure out a few things and I am wicked lost.

  1. Can I limit the text to 5 characters and how?

  2. Can I have a colon embedded in the code so that it can't be deleted by the user?

  3. Finally, can I take that code and verify that it is only the digits (ignoring the colon of course)


Solution

  • The answer is to use a JFormattedTextField and a MaskFormatter.

    For example:

    String mask = "##:##";
    MaskFormatter timeFormatter = new MaskFormatter(mask);
    JFormattedTextField formattedField = new JFormattedTextField(timeFormatter);
    

    The Java compiler will require that you catch or throw a ParseException when creating your MaskFormatter, and so be sure to do this.