TextField输入数字及星号的问题。
今天看了一个程序里有个密码输入TextField,输入的时候显示的是星号,但是又控制了只能输入数字,不知是怎么实现的,我知道用.password是星号,但是不能限制只允许输入数字,请教各位大虾如何实现这个功能啊。
------解决方案--------------------参考下面的
a = new JTextField(5);
a.setDocument(new OnlyDigit(a));
/**
* this class is used to restrict the input, it makes sure that
* the text of the text field is a digit string.that is, 'a ', 'Z ',
* '_ ', '$ 'and so on are all forbidden.
* @author feng
*
*/
private class OnlyDigit extends PlainDocument{
private JTextField f;
public OnlyDigit(JTextField f){
this.f = f;
}
public void insertString(int offset,
String str,
AttributeSet attSet)
throws BadLocationException{
StringBuffer tmp = new StringBuffer(f.getText());
tmp.insert(offset,str);
Pattern p = Pattern.compile( "^-?\\d*(\\.)?\\d*$ ");
Matcher m = p.matcher(tmp.toString());
if(m.find()){
super.insertString(offset,str,attSet);
}
}
}