I can not delete the input of a JFormattedTextField

1

I'm doing a program and it uses some formatted JTextFields, that is, JFormatedTextField that calls a MaskFormatter. The problem is that when writing a message and trying to delete it, the message comes back, making it impossible to leave the field empty again. Does anyone have a solution for this? Here is the code I'm using:

package main;

import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;

public class NewScheduleWindow extends JFrame{

JTextField hourField = new JTextField();

public NewScheduleWindow(){

    try {
        hourField = new JFormattedTextField(new MaskFormatter("##:##"));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    add(hourField);
    hourField.setBounds(160, 65, 42, 25);
    hourField.setFont(Reference.setDefaultFont(15));
    hourField.requestFocus();

    //Etc...
    
asked by anonymous 02.12.2014 / 21:38

1 answer

1

Take a look at in this article .

The author implements a AllowBlankMaskFormatter made for this type of situation.

AllowBlankMaskFormatter abmf = new AllowBlankMaskFormatter("##:##");
ambf.setAllowBlankField(true);
hourField = new JFormattedTextField(abmf); 

Another alternative (as per this issue in SOEn ) is to set the policy in case loss of focus to COMMIT :

hourField.setFocusLostBehavior(JFormattedTextField.COMMIT);

This will leave the "invalid" blank value visible.

You can then call the method commitEdit manually and, in case of an exception, reset the value to null:

try {
    hourField.commitEdit();
} catch (ParseException e) {
    // qualquer edição inválida reseta o valor
    // você pode também checar apenas pelo pattern padrão de campo vazio
    hourField.setValue(null);
}

I do not like this second solution for a number of reasons (use of common flow exceptions, display of invalid values, breaking the principle of least knowledge, etc.). I recommend the first solution.

    
03.12.2014 / 00:01