Friday, January 20, 2006

how to attach a MaskFormatter to a JFormattedTextField in the IDE's form editor?

Un pequeño tutorial de como manejar validaciones con java Studio Entreprise, puesto que me fue un poco trabajoso tuve que preguntarle al soporte como se hacia, y realmente es sencillo pero muy elaborado. Esta en ingles espero que se entienda ;-)

how to attach a MaskFormatter to a JFormattedTextField in the IDE's form editor?

1. Add JFormattedTextField to the form.

2. In Properties window, click ... button for formatterFactory property.

3. Select User Code radio button.

4. Enter the following example text into the text area:



new javax.swing.JFormattedTextField.AbstractFormatterFactory() {

public javax.swing.JFormattedTextField.AbstractFormatter

getFormatter(javax.swing.JFormattedTextField tf) {

try {

return new javax.swing.text.MaskFormatter("##-###");

} catch (java.text.ParseException pe) {

pe.printStackTrace();

}

return null;

}

}



5. Build and run the project and you've got a formatted text field that only accepts two digits, a hyphen, and three more digits (the hyphen is automatically inserted by the formatter).



--> On the other hand, are you asking how to validate the input when the form in which the formatted text field is contained is somehow dismissed (e.g. if the field were in a dialog In that case, the code which built and displayed the dialog will need an action listener on the button which accepts the user input, and this listener will retrieve the text from the field, validate it, and if it is incorrect, either display a message in a new dialog, or show an error message in a JLabel near the bottom or top of the dialog (commonly seen in Studio itself). If the input is valid, then dispose of (i.e. close) the original dialog and proceed as normal with the given user input.


--> Or, do you want to verify the input before the field loses focus? In that case, click the ... button next to the inputVerified property for the text field and add something like the following for the User Code:


new javax.swing.InputVerifier() {

public boolean verify(javax.swing.JComponent input) {

// validate user input

return true;

}

}

The code displaying the input dialog would need a counter, incremented each time the input was invalid, and show the error dialog only on the third attempt.


En forma de Bean

import java.awt.event.FocusListener;

import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;

public class MaskFormattedTextField extends JFormattedTextField
implements java.io.Serializable {
private String mask = "";

public MaskFormattedTextField() {
addFocusListener(new FocusListener() {
public void focusGained(java.awt.event.FocusEvent e) {
selectAll();
}
public void focusLost(java.awt.event.FocusEvent e) {}
});
}

public final String getMask() {
return mask;
}

public final void setMask(final String m) {
mask = m;

try {
new MaskFormatter(mask).install(this);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
}
}

3 comments:

12345 said...

Hola, soy nuevo en java y quiero preguntar, como se hace para restringir el ingreso en un jtextfield a sólo números??? (sea este por teclado o vía pegado del portapapeles de windows) Es decir el usuario solo puedeingresar números, y el caso contrario, solo texto, nada de números??? A proposito, estoy utilizando netbeans.
Gracias

Victor Sosa said...

Gino:
jtextfield no soporta estas restricciones, para hacer esto tienes que usar JFormattedTextField con en esta en ejemplo.

Y si puedes utilizar netbeans para eso :) eso no depende de IDE. (Por cierto Java Studio Enterprise esta basado en Netbeans).

Tim said...

In case you want to take this a step further, you can add an inputverifier to your text field to validate that it is an email address.
I have an example of doing this to validate that an email address entered is of the appropriate format at:
http://timarcher.com/?q=node/36