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);
}
});
}
}
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
Here I created a mask selected by number, now the keyListener
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!