随便写了个,能满足你的需要,细节问题自已看着办吧/* * Created on 2005-7-4 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package common.test;import javax.swing.*; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument;/** * @author chenxw * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class MyText extends JFrame { private JTextField aText = new JTextField(); public MyText(){ aText.setDocument(new customDoc()); this.getContentPane().add(aText); this.setSize(100,100); this.setVisible(true); }
class customDoc extends PlainDocument{ public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { for(int i=0;i<str.length();i++){ if(str.charAt(i)<'0'||str.charAt(i)>'9'){ return ; } } super.insertString(offs,str,a); } } public static void main(String[] args) { MyText mytext = new MyText(); } }
* Created on 2005-7-4
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package common.test;import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;/**
* @author chenxw
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class MyText extends JFrame {
private JTextField aText = new JTextField();
public MyText(){
aText.setDocument(new customDoc());
this.getContentPane().add(aText);
this.setSize(100,100);
this.setVisible(true);
}
class customDoc extends PlainDocument{
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
for(int i=0;i<str.length();i++){
if(str.charAt(i)<'0'||str.charAt(i)>'9'){
return ;
}
}
super.insertString(offs,str,a);
}
}
public static void main(String[] args) {
MyText mytext = new MyText();
}
}