jtextfield怎么限制输入的个数
求哪位高手帮我看下,为什么我这样写不可以?package test;
import java.util.*;
import javax.print.attribute.AttributeSet;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.*;
import java.awt.event.*;
public class Test10 extends JFrame{
JPanel panel;
JLabel label[]=new JLabel[2];
JTextField textField[]=new JTextField[2];
public Test10(){
super("生成查询条件");
setUpUIComponent();
//setUpEventListener();
}
public void setUpUIComponent(){
panel=new JPanel();
label[0]=new JLabel("账号");
label[1]=new JLabel("密码");
textField[0]=new JTextField();
textField[1]=new JTextField();
AbstractDocument ad=(AbstractDocument)textField[0].getDocument();
ad.setDocumentFilter(new DocoumentSizeFilter(10));
for(int i=0;i<label.length;i++){
panel.add(label[i]);
panel.add(textField[i]);
}
panel.setLayout(null);
label[0].setBounds(10,10,50,30);
label[1].setBounds(10,50,50,30);
textField[0].setBounds(50,10,150,30);
textField[1].setBounds(50,50,150,30);
this.add(panel);
this.setSize(400,200);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new Test10();
}
}
class DocoumentSizeFilter extends DocumentFilter{
int maxLength;
public DocoumentSizeFilter(int maxLength){
this.maxLength=maxLength;
}
public void insertString(DocumentFilter.FilterBypass fb,int offset, String string,AttributeSet attr)throws BadLocationException{
if(fb.getDocument().getLength()+string.length()<=maxLength){
super.insertString(fb, offset,string,null);
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
public void replace(DocumentFilter.FilterBypass fb,int offset,int length,String text,AttributeSet attrs)throws BadLocationException{
if(fb.getDocument().getLength()+text.length()-length<=maxLength){
super.replace(fb, offset, length, text, null);
}
else{
Toolkit.getDefaultToolkit().beep();
}
}
}