当前位置: 技术问答>java相关
如何设置TextField或JTextField,使其只能输入规定个数的字符?
来源: 互联网 发布时间:2015-04-27
本文导语: 请各位多帮忙! | TextField jt = new TextField(); jt.addKeyListener(new KeyListener(){ public void keyTyped(KeyEvent e){ } public void keyPressed(Ke...
请各位多帮忙!
|
TextField jt = new TextField();
jt.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e){
}
public void keyPressed(KeyEvent e){
if(jt.getText().length()>3){
System.out.println("OK");
e.consume();
}
}
public void keyReleased(KeyEvent e){
}
});
}
AWT的可以通过添加KeyListener来实现,Swing的应该继承Document接口来实现用KeyListener好象就不行了.
jt.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e){
}
public void keyPressed(KeyEvent e){
if(jt.getText().length()>3){
System.out.println("OK");
e.consume();
}
}
public void keyReleased(KeyEvent e){
}
});
}
AWT的可以通过添加KeyListener来实现,Swing的应该继承Document接口来实现用KeyListener好象就不行了.
|
先定义一个NumberDocument类:
public class NumberDocument extends PlainDocument
{
public void insertString(int offset,String s,AttributeSet attributeSet)
throws BadLocationException
{
try{
if(!s.equals (".") && !s.equals ("-"))
{
Integer.parseInt(s,10);
}
String src=/tech-qa-java/this.getText(0,this.getLength ());
Double.parseDouble (src.substring (0,offset)+s+src.substring (offset,src.length ()));
}catch(Exception ex)
{
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString (offset,s,attributeSet);
}
}
怎么用它呢:
JTextField txtfield = new JTextField();
txtfield.setDocument(NumberDocument);
OK!
public class NumberDocument extends PlainDocument
{
public void insertString(int offset,String s,AttributeSet attributeSet)
throws BadLocationException
{
try{
if(!s.equals (".") && !s.equals ("-"))
{
Integer.parseInt(s,10);
}
String src=/tech-qa-java/this.getText(0,this.getLength ());
Double.parseDouble (src.substring (0,offset)+s+src.substring (offset,src.length ()));
}catch(Exception ex)
{
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString (offset,s,attributeSet);
}
}
怎么用它呢:
JTextField txtfield = new JTextField();
txtfield.setDocument(NumberDocument);
OK!