Here are two options:
A JTextField
with an InputVerifier
. The text field will not yield focus unless its contents are of the form specified.
JTextField textField = new JTextField();
textField.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
if (text.matches("%\\d\\d"))
return true;
return false;
}
});
textField.setText("% ");
A JFormattedTextField
with a MaskFormatter
. The text field will not accept typed characters which do not comply with the mask specified. You ca set the placeholder character to a digit if you want a default number to appear when there is no input.
MaskFormatter mask = new MaskFormatter("%##");
mask.setPlaceholderCharacter(' ');
JFormattedTextField textField2 = new JFormattedTextField(mask);