用户自定义一个异常,编程创建并抛出某个异常类的实例。运行该程序并观察执行结果。
例:用户密码的合法化验证。
要求密码有4-6个数字组成。若长度不落在这个范围或不是有数字组成。抛出自己的异常。
要求:
1.面向对象编程。
2.异常定义,抛出,捕捉三个流程。
package shiyan;
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PassWord {
private String password;
private JButton loginButton;
private JTextField passwordText;
private JLabel tipLabel;
public PassWord()
{
CreateWindow();
}
public static void main(String[] args)
{
PassWord zhouwei = new PassWord();
zhouwei.action();
}
public void CreateWindow() {
//创建窗口
JFrame frame = new JFrame("窗口");
frame.setSize(600, 400);//设置框架大小
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setDefaultCloseOperation()是设置用户在此窗体上发起 "close" 时默认执行的操作。
//EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit 方法退出应用程序。仅在应用程序中使用。
//创建面板
JPanel panel1 = new JPanel();//可以创建多个面板并在 JFrame 中指定位置,面板中我们可以添加文本字段,按钮及其他组件。
frame.add(panel1);// 添加面板
panel1.setLayout(null);//设置布局为 null
// 创建账号 JLabel
JLabel userLabel = new JLabel("账号:");
userLabel.setBounds(180,20,80,25);//setBounds(x, y, width, height)定义了组件的位置,x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。。
panel1.add(userLabel);//添加JLabel
//创建文本域用于输入账号
JTextField userText = new JTextField(100);
userText.setBounds(210,20,165,25);
panel1.add(userText);//添加账号的文本域
// 创建密码 JLabel
JLabel passwordLabel = new JLabel("密码:");
passwordLabel.setBounds(180,50,80,25);
panel1.add(passwordLabel);
/*
*这个类似用于输入的文本域
* 但是输入的信息会以点号代替,用于包含密码的安全性
*/
//创建文本域用于输入密码
passwordText = new JPasswordField(100);// 创建输入密码的文本域
passwordText.setBounds(210,50,165,25);
panel1.add(passwordText);// // 添加输入密码的文本域
// 创建登录按钮
loginButton = new JButton("注册");
loginButton.setBounds(250, 80, 80, 25);
panel1.add(loginButton);
//提示文本域
tipLabel = new JLabel("");// 创建 JLabel
tipLabel.setBounds(180,100,300,25);//setBounds(x, y, width, height)定义了组件的位置,x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。width越大可输入的字数越多
panel1.add(tipLabel);//添加JLabel
frame.setVisible(true);// 设置界面可见
}
//鼠标点击事件,try ,捕获异常
public void action() {
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
password = passwordText.getText().trim();
try {
Check();
tipLabel.setText("注册成功");
}catch (PasswordException e1) {
tipLabel.setText(e1.getMessage());
}
}
});
}
//检查输入是否有误,有误就抛错
public void Check()throws PasswordException
{
if((password.length()<4 || password.length()>6) && (!password.matches("\\d*")))
{
throw new PasswordException("输入数字个数应为4-6个且只能输入数字");
}
if(password.length()<4 || password.length()>6)
{
throw new PasswordException("输入数字个数应为4-6个");
}
if(!password.matches("\\d*"))
{
throw new PasswordException("只能输入6个数字");
}
}
//自定义异常类
public class PasswordException extends Exception
{
public PasswordException(String str) {
super(str);
}
public PasswordException() {
}
}
}