找了半天没找到,给说下
在单行输入框内怎么样只能输入0-9的数字,别的都丢弃!
import javax.swing.text.PlainDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.AttributeSet;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class InsertNumberTest extends JFrame{
private JTextField jtfNumber;
public InsertNumberTest(){
setTitle("numberTextField");
jtfNumber=new JTextField();
jtfNumber.setDocument(new NumberDocument());
getContentPane().add(jtfNumber,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(150,80);
setVisible(true);
}
public static void main(String[] args){
new InsertNumberTest();
}
}
class NumberDocument extends PlainDocument{
public void insertString(int off,String str,AttributeSet attr) throws BadLocationException{
if(str==null) return;
int c=0;
char[] chars=str.toCharArray();
for(int i=0;i<chars.length;i++){
if(Character.isDigit(chars[i])){
chars[c++]=chars[i];
}
}
super.insertString(off,new String(chars,0,c),attr);
}
}