Maskformatter leaving empty space

Asked

Viewed 586 times

0

In my project, I have an age field, where I want to receive at most 3 number, so I did this :

mskIdade = new MaskFormatter("###");

so far so good, but every time I type a number with less than 3 characters, the mskIdade fills the remaining fields with empty spaces (" "). I’m pretty sure that’s because ### oblige the field to be left with three characters. As I can not force the field to be 3 characters long and accept it only numbers ?

  • Didn’t you want to leave the OOP question? I was answering

2 answers

6


You can use the Trim() in your String, to remove left and right empty spaces from the value:

String str = formattedTextField.getText().trim();

Another way, maybe it’s even better to give you more control than is typed, is by using the class Plaindocument. With it, you not only control the amount of characters you type, but you also want just numbers:

class JTextFieldLimit extends PlainDocument {

    private int limit;

    JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }

        if ((getLength() + str.length()) <= limit) {

            super.insertString(offset, str.replaceAll("\\D++", ""), attr);
        }
    }
}

Then just apply to any JTextfield:

    JTextFieldLimit limitDocument = new JTextFieldLimit(3);
    seuTextField.setDocument(limitDocument);

The signature of the method insertString receives three parameters:

  • int offset = indicates which index of the current string in the field, the new will be added;

  • String str = is the new string that will be added (digits, in your case);

  • AttributeSet attr = are attributes of the string(like font type, font size and style, etc...), in this case, it made no difference to us.

In the str.replaceAll("\\D++", ""), I’m passing a Regular Expression that will remove any characters passed in the string that are not digits.

Remembering that the class builder JTextFieldLimit receives the character limit your field may have, and this class can be used in any text field.

Obs.: With the class shown above, you don’t need to use or MaskFormatter and neither JTextFormatterField.

References:

Limit Jtextfield input to a Maximum length(java2s)

How to implement in Java ( Jtextfield class ) to allow entering only digits?

Limiting the number of characters in a Jtextfield

  • Good ! I was left with a small doubt : What would be the elements int offset and AttributeSet attr ? Are parameters that already come loaded when you load the method, or it was you who put them there ?

  • @Danielsantos offset is the current position of the cursor where the string will be inserted. Looking at this picture of the doc is easier to understand. AttributeSet are features of the string that will be added (like font, size, etc...).

1

I’ve made two methods that can help you with this problem:

Check if there are only numbers in a String.

public static boolean apenasNumeros(String text){
    return text.matches("[0-9]+");
}

Return only the numbers of a String.

public static String tirarTudoExcetoDigitos( String text) {
       if (text == null || text.length() == 0) {
           return "";
       }
       return text.replaceAll("\\D+", "");
    }

Small example:

public static void main(String[] args) {
    String test1 = "12345";
    System.out.println("Teste 1:");
    System.out.println("Apenas Números? " + apenasNumeros(test1));
    System.out.println("Apenas Números!! " + tirarTudoExcetoDigitos(test1));
    String test2 = "123A5";
    System.out.println("Teste 2:");
    System.out.println("Apenas Números? " + apenasNumeros(test2));
    System.out.println("Apenas Números!! " + tirarTudoExcetoDigitos(test2));
}

Upshot:

Teste 1:
Apenas Números? true
Apenas Números!! 12345
Teste 2:
Apenas Números? false
Apenas Números!! 1235
  • There is only one problem with this answer: how will you apply this method to the field? Although filtering correctly, the field will continue to allow you to type anything. The purpose of maskformatter(and plaindocument) is neither to let the user type what they cannot, rather than having to filter after they type.

Browser other questions tagged

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