Autocomplete zeros before number in maskFormatter

277 views Asked by At

I'm using a mask to accept codes as CUIL (Argentina) that has the following format ##-########-#. But there's a posibility that the middle number has 7 numbers instead of 8, so what i want to do is that when the user press "-" or right arrow autocomplete a 0 at the begining of the middle number.

Example:

The user types 20-1523245

Then the user press - and the result is 20-01523245-

And it's important that the cursor remains in the last position to write the last number. 20-01523245-2

I've tried to do this with KeyListener but I have a problem because the mask disapear when i put the value with the 0, and also I don't know if that is the best way to do it

I left you the code, Thanks

public class JQFormattedTextField extends JFormattedTextField implements KeyListener {


private static final long serialVersionUID = 1L;
private JQFormats format;
private Map<JQFormats,String> formatMap;

public JQFormattedTextField(){
    super();
    addKeyListener(this);
    createMap();
}

public JQFormattedTextField(JQFormats format){
    this();
    setFormat(format);
}

public void setFormat(JQFormats format){
    this.format=format;
    try {
          MaskFormatter mask = new MaskFormatter(formatMap.get(format));
          mask.install(this);

        } catch (ParseException ex) {
            System.out.println("Error creating the mask with the passed format");
      }

}

public JQFormats getFormat(){
    return format;
}

public void createMap(){

    formatMap = new HashMap<JQFormats,String>();
    formatMap.put(JQFormats.CUIL, "##-########-#");
    formatMap.put(JQFormats.CUIT, "##-########-#");
    formatMap.put(JQFormats.DNI, "##.###.###");
    formatMap.put(JQFormats.FECHA,"##/##/####");
    formatMap.put(JQFormats.IMPORTE_2DECIMALES, "####.##");
}


@Override
public void keyPressed(KeyEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.getKeyCode() == KeyEvent.VK_MINUS || arg0.getKeyCode() == 39){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                StringBuilder s = new StringBuilder(getText());
                s.setCharAt(3,'0');
                setValue(s.toString());
                setFormat(format);
            }
        });
    }
}
1

There are 1 answers

0
Lenin On

I find the solution, maybe someone is interested. It's a bit specific for each maskFormatter but it works. I will post how I do the date format because the other are too specifics formats for Argentina

public class JQDateTextField extends JFormattedTextField {


/**
 * Creates a JQFechaTextField that extends from JQFormattedTextField with a date mask chosen
 * The options are: ##/##/#### - specify int 1 , ##/#### - specify int 2
 * The JQFechaTextField will be autocompleted if the user types one digit in day or month and press '-', '/' or right arrow
 */
public JQFechaTextField(int maskNumber){
    super();
    jqftf = this;
    this.maskNumber=maskNumber;
    if(maskNumber==2){
        setFormat("##/####"); 
    }
    else{
        setFormat("##/##/####");  //Default format
    }
    addKeyListener(this);
}

Here I created a mask selected by number, now the keyListener

@Override
public void keyPressed(KeyEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.getKeyCode() == KeyEvent.VK_MINUS || arg0.getKeyCode() == 39 || arg0.getKeyCode() == 191 
            || arg0.getKeyCode() == KeyEvent.VK_SUBTRACT){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String s = getText().replaceAll("\\s","");
                String parts[] = s.split("/");

                if(s.length()==3 && maskNumber!=2 || s.length()==2 && maskNumber==2){
                    String aux = String.format("%02d",Integer.parseInt(parts[0]));
                    jqftf.setText(aux);
                }
                if(s.length()==5 && maskNumber!=2){
                    String aux = String.format("%02d",Integer.parseInt(parts[1]));
                    String aux2 = parts[0] + aux;
                    jqftf.setText(aux2);
                }
            }
        });
    }
}

I used the split function to separate the string in parts, only taking the numbers. Then I format the numbers into the quantity of digits I wanted (2 for day and month) with String.format, and then concat the parts again. Remember jqftf has a mask so I must not add '/' or '-' characters in the inserted String

Thats all, I hope it could help you

Regards!