I cannot delete input from a Jformattedtextfield

Asked

Viewed 692 times

1

I am making a program and it uses some formatted Jtextfields, that is, Jformatedtextfield that calls a Maskformatter. The problem is that by writing a message and trying to erase it, the message returns, making it impossible to leave the field empty again. Does anyone have a solution for this? Here’s 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...

1 answer

1


Take a look in that article.

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

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

Other alternative (as appropriate that question in Soen) is to set the policy in case of loss of focus to COMMIT:

hourField.setFocusLostBehavior(JFormattedTextField.COMMIT);

This will leave the "invalid" blank visible.

You can then call the method commitEdit manually and, in case of 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 don’t like this second solution for a number of reasons (use of common flow exceptions, display of invalid values, break the principle of minimum knowledge, etc.). I recommend the first solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.