14.密码文本框和密码确认密码校验

效果:

package com.lvshitech.gui;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;

@SuppressWarnings("serial")
public class JPasswordFieldDemo extends JApplet implements ActionListener {

	JLabel jl1, jl2;
	JPasswordField jp1, jp2;
	JButton jb1, jb2;
	
	public void init() {
		// 容器
		Container container = getContentPane();
		container.setLayout(new GridLayout(3, 2));
		
		// 标签
		jl1 = new JLabel("<html><h3>请输入您的密码:</h3></html>", JLabel.CENTER);
		jl2 = new JLabel("<html><h3>请再次输入密码:</h3></html>", JLabel.CENTER);
		
		// 文本框
		jp1 = new JPasswordField(8);
		jp2 = new JPasswordField(8);
		
		// 按钮
		jb1 = new JButton("<html><h3>提交</h3></html>");
		jb2 = new JButton("<html><h3>取消</h3></html>");
		
		// 添加到容器
		container.add(jl1);
		container.add(jp1);
		container.add(jl2);
		container.add(jp2);
		container.add(jb1);
		container.add(jb2);
		
		// 事件
		jb1.addActionListener(this);
		jb2.addActionListener(this);
	}
	
	// 实现事件监听器
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jb1) {
			String pwd1 = String.valueOf(jp1.getPassword());
			String pwd2 = String.valueOf(jp2.getPassword());
			if ("".equals(pwd1) || "".equals(pwd2)) {
				showStatus("密码不能为空!");
			} else {
				if (pwd1.equals(pwd2)) {
					showStatus("密码输入正确!");
				} else {
					showStatus("两次输入的密码不同,请重新输入!");
					jp1.setText("");
					jp2.setText("");
				}
			}
		}
		if (e.getSource() == jb2) {
			jp1.setText("");
			jp2.setText("");
			showStatus("");
		}
	}
}

 

posted @ 2018-01-15 23:43  半生戎马,共话桑麻、  阅读(264)  评论(0)    收藏  举报
levels of contents