主要是给文本框加个键盘监听器 public void keyReleased(KeyEvent e) {
} public void keyTyped(KeyEvent e) { // text1.setText("123456789"); } public void keyPressed(KeyEvent e) { char k=e.getKeyChar(); if ((k>='A' && k<= 'z') || (k>='0' && k<='9')|| k == '_') { //JOptionPane.showMessageDialog(null,"正常");
} else text1.setText(""); }
我想用正则表达式实现,在SWING中设计
/** * 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); } } }---------------- a = new JTextField(5); //...... a.setDocument(new OnlyDigit(a));
还是在网页中啊?
要是用的是AWT.SWING的话,用TextListener 中的void textValueChanged(TextEvent e) 方法。
Pattern p = Pattern("[^w\-]");
应该用这个吧,。初学。
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
// text1.setText("123456789");
}
public void keyPressed(KeyEvent e)
{
char k=e.getKeyChar();
if ((k>='A' && k<= 'z') || (k>='0' && k<='9')|| k == '_')
{
//JOptionPane.showMessageDialog(null,"正常");
}
else
text1.setText("");
}
* 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);
}
}
}---------------- a = new JTextField(5);
//......
a.setDocument(new OnlyDigit(a));
正则只能匹配,不能帮你删除清空
配合后台正好