| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 480 人关注过本帖
标题:jtextfield怎么限制输入的个数
只看楼主 加入收藏
暂不存在
Rank: 1
等 级:新手上路
帖 子:21
专家分:0
注 册:2013-5-30
结帖率:75%
收藏
 问题点数:0 回复次数:0 
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();
        }
    }
}
搜索更多相关主题的帖子: package public import 
2014-03-09 16:58
快速回复:jtextfield怎么限制输入的个数
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.048475 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved