利用Document构造JPasswordField:

利用Document构造JPasswordField:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JPasswordField3{

    public static void main(String args[])    {

    	JFrame f = new JFrame("JPasswordField3");
    	Container contentPane = f.getContentPane();
    	contentPane.setLayout(new BorderLayout());

    	JPanel p1 = new JPanel();        
    	//p1.setLayout(new GridLayout(4,2));
    	p1.setLayout(new GridBagLayout());
    	GridBagConstraints gbc = new GridBagConstraints();
    	gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
    	gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
    	
    	p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));         
    	JLabel l1 = new JLabel("姓名:");        
    	JLabel l2 = new JLabel("性别:");        
    	JLabel l3 = new JLabel("身高:");        
    	JLabel l4 = new JLabel("体重:");        
    	JPasswordField t1 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(10),"",10);
    	JPasswordField t2 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(1),"",2);
    	JPasswordField t3 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);        
    	JPasswordField t4 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);

    	gbc.gridy=1;
    	gbc.gridx=0;
    	p1.add(l1,gbc);
    	gbc.gridx=1;
    	p1.add(t1,gbc);
    	gbc.gridy=2;
    	gbc.gridx=0;
    	p1.add(l2,gbc);
    	gbc.gridx=1;
    	p1.add(t2,gbc);
    	gbc.gridy=3;
    	gbc.gridx=0;        
   	    p1.add(l3,gbc);
   	    gbc.gridx=1;
    	p1.add(t3,gbc);
    	gbc.gridy=4;
    	gbc.gridx=0;        
    	p1.add(l4,gbc);
    	gbc.gridx=1;
    	p1.add(t4,gbc);        
    	
    	contentPane.add(p1);        
    	f.pack();        
    	f.show();        
    	f.addWindowListener(new WindowAdapter() {            
    		public void windowClosing(WindowEvent e) {                    
    			System.exit(0);            
    		}        
    	});    
    }
}
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;

public class JPasswordField3_OnlyNumberDocument extends PlainDocument{

	private int maxLength;
	int result;
	
	public JPasswordField3_OnlyNumberDocument(int maxLength){
		this.maxLength = maxLength;
	}
	
	public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
	{
		for(int i=0;i<=9;i++){
			result = Integer.toString(i).compareTo(str);
			if (result == 0){ //是数字才处理

			  if ( getLength() + str.length() > maxLength ){
		   		Toolkit.getDefaultToolkit().beep();
			  }else{
				super.insertString(offset,str,att);
			  }	
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值