So I have a JFormattedTextField
and I need to restrict the user from entering anything b开发者_开发技巧ut letters and hyphens. I'm not quite sure how to use the MaskFormatter
without explicitly knowing the length of the string that is to be entered.
My code currently looks like this:
MaskFormatter formatter = new MaskFormatter();
formatter.setValidCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabscedfghijklmnopqrstuvwxyz-");
JFormattedTextField firstNameTextField = new JFormattedTextField(formatter);
When I call firstNameTextField.setText(getName())
, the text does not get set, leaving me with an unusable, empty text field.
Any help would be greatly appreciated. Thanks.
Since you want no commitment in terms of string length, i have the impression, that it is a lot easier to achieve the effect of a JFormattedTextField and its MaskFormatter, if you use a regular JTextField and a KeyListener with its KeyAdapter. You can check each keystroke against the allowed character string and either accept the character or beep.
Hey i had a similar problem and what i used instead of jFormatter was jTextfield and acheived the same with keyListener
Heres the code
jTextFieldName.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent evt) {
char c = evt.getKeyChar();
if(!Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE) || (c==KeyEvent.VK_DELETE))
{
f.getToolkit().beep();
evt.consume();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
});
Here 'f' is nothing but JFrame
精彩评论