Search code examples
javadate-formatmaskformatter

java mask format textfield date


I am trying to make textField with dateFormat like (08/06/2015). But the problem is whenever i delete the field or press tab it becomes normal textField again. Is there anyway make the / undeletable? thanks

private static final DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    textF = new JFormattedTextField(dateFormat); 


MaskFormatter dateMask;
    try {
        dateMask = new MaskFormatter("##/##/####");
        dateMask.install(textF);
        dateMask.setValidCharacters("0123456789");
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    textF.setHorizontalAlignment(JTextField.RIGHT);

Solution

  • try with this

    MaskFormatter dateMask;
    try {
        dateMask = new MaskFormatter("##/##/####");
        dateMask.setPlaceholderCharacter('/');
        dateMask.setValidCharacters("0123456789");
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    textF = new JFormattedTextField(dateMask ); 
    textF.setHorizontalAlignment(JTextField.RIGHT);