25 API-GUI(事件监听机制,适配器模式),Netbeans的概述和使用(模拟登陆注册GUI版)

来源:互联网 发布:4g网络优化师 编辑:程序博客网 时间:2024/06/06 03:52

 1:GUI(了解)

(1)用户图形界面
GUI:方便直观
CLI:需要记忆一下命令,麻烦
(2)两个包:
java.awt:和系统关联较强  ,属重量级控件

javax.swing:纯Java编写,增强了移植性,属轻量级控件。

(3)GUI的继承体系
组件:组件就是对象
容器组件:是可以存储基本组件和容器组件的组件。
基本组件:是可以使用的组件,但是必须依赖容器。

(4)事件监听机制(理解)

A:事件源
B:事件
C:事件处理

D:事件监听

事件监听机制:A:事件源事件发生的地方B:事件就是要发生的事情C:事件处理就是针对发生的事情做出的处理方案D:事件监听 就是把事件源和事件关联起来举例:人受伤事件。事件源:人(具体的对象)Person p1 = new Person("张三");Person p2 = new Person("李四");事件:受伤interface 受伤接口 {一拳();一脚();一板砖();}事件处理:受伤处理类 implements 受伤接口 {一拳(){ System.out.println("鼻子流血了,送到卫生间洗洗"); }一脚(){ System.out.println("晕倒了,送到通风处"); }一板砖(){ System.out.println("头破血流,送到太平间"); }}事件监听:p1.注册监听(受伤接口)

窗体布局


l简单的窗体创建过程:
•Frame  f = new Frame(“my window”);//创建窗体对象
•f.setLayout(new FlowLayout());//指定窗体布局
•f.setSize(300,400);//设置窗体大小
•f.setLocation(300,200);//设置窗体出现在屏幕的位置
•f.setVisible(true);//设置窗体可见

创建一个带关闭功能的窗体(添加对窗体的监听对窗体关闭)

import java.awt.Frame;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;public class FrameDemo {public static void main(String[] args) {// 创建窗体对象Frame f = new Frame("窗体关闭案例");// 设置窗体属性f.setBounds(400, 200, 400, 300);// 让窗体关闭//事件源//事件:对窗体的处理//事件处理:关闭窗口(System.exit(0));//事件监听//用适配器类改进f.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});// 设置窗体可见f.setVisible(true);}}


(5)适配器模式(理解)

A:接口
B:抽象适配器类

C:实现类

接口

/* * 针对用户操作的四种功能 */public interface UserDao {public abstract void add();public abstract void delete();public abstract void update();public abstract void find();}

接口实现类

public class UserDaoImpl implements UserDao {@Overridepublic void add() {System.out.println("添加功能");}@Overridepublic void delete() {System.out.println("删除功能");}@Overridepublic void update() {System.out.println("修改功能");}@Overridepublic void find() {System.out.println("查找功能");}}

抽象适配器类

public abstract class UserAdapter implements UserDao {@Overridepublic void add() {}@Overridepublic void delete() {}@Overridepublic void update() {}@Overridepublic void find() {}}

继承适配器(实现接口指定功能)类

public class UserDaoImpl2 extends UserAdapter {@Overridepublic void add() {System.out.println("添加功能");}}

测试调用类

/* * 问题: * 接口(方法比较多) -- 实现类(仅仅使用一个,也得把其他的实现给提供了,哪怕是空实现) * 太麻烦了。 * 解决方案: * 接口(方法比较多) -- 适配器类(实现接口,仅仅空实现) -- 实现类(用哪个重写哪个) */public class UserDaoDemo {public static void main(String[] args) {UserDao ud = new UserDaoImpl();ud.add();// 我没有说我们需要四种功能都实现啊。UserDao ud2 = new UserDaoImpl2();ud2.add();}}



(6)案例:
A:创建窗体案例
B:窗体关闭案例
C:窗体添加按钮并对按钮添加事件案例。
界面中的组件布局。
D:把文本框里面的数据转移到文本域
E:更改背景色
F:设置文本框里面不能输入非数字字符
G:一级菜单
H:多级菜单

(7)Netbeans的概述和使用

A:是可以做Java开发的另一个IDE工具。

1:如何让Netbeans的东西Eclipse能访问。
在Eclipse中创建项目,把Netbeans项目的src下的东西给拿过来即可。
注意:修改项目编码为UTF-8

B:使用

A:四则运算

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package cn.itcast.view;import cn.itcast.util.UiUtil;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;/** * * @author Administrator */public class NewJFrame extends javax.swing.JFrame {    /**     * Creates new form NewJFrame     */    public NewJFrame() {        initComponents();        init();    }         public NewJFrame(String name) {        initComponents();        init(name);    }    private void init() {        this.setTitle("模拟四则运算");        UiUtil.setFrameImage(this,"jjcc.jpg");        UiUtil.setFrameCenter(this);    }         private void init(String name) {        this.setTitle("欢迎"+name+"光临");        UiUtil.setFrameImage(this,"jjcc.jpg");        UiUtil.setFrameCenter(this);    }    /**     * This method is called from within the constructor to initialize the form.     * WARNING: Do NOT modify this code. The content of this method is always     * regenerated by the Form Editor.     */    @SuppressWarnings("unchecked")    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents    private void initComponents() {        jLabel1 = new javax.swing.JLabel();        jLabel2 = new javax.swing.JLabel();        jLabel3 = new javax.swing.JLabel();        firstNumber = new javax.swing.JTextField();        secondNumber = new javax.swing.JTextField();        resultNumber = new javax.swing.JTextField();        jLabel4 = new javax.swing.JLabel();        selectOperator = new javax.swing.JComboBox();        jButton1 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jLabel1.setText("第一个操作数");        jLabel2.setText("第二个操作数");        jLabel3.setText("结果");        jLabel4.setText("=");        selectOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-", "*", "/" }));        jButton1.setText("计算");        jButton1.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton1ActionPerformed(evt);            }        });        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGap(26, 26, 26)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                    .addComponent(firstNumber)                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addComponent(selectOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)                    .addComponent(secondNumber))                .addGap(14, 14, 14)                .addComponent(jLabel4)                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                    .addComponent(jButton1)                    .addComponent(jLabel3)                    .addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))                .addContainerGap(23, Short.MAX_VALUE))        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addContainerGap()                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel1)                    .addComponent(jLabel2)                    .addComponent(jLabel3))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(firstNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel4)                    .addComponent(selectOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(18, 18, 18)                .addComponent(jButton1)                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))        );        pack();    }// </editor-fold>//GEN-END:initComponents    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed        //获取第一个操作数        String firstNumberString = this.firstNumber.getText().trim();        //获取运算符        String selectOperator = this.selectOperator.getSelectedItem().toString();        //获取第二个操作数        String secondNumberString = this.secondNumber.getText().trim();//        System.out.println(firstNumberString);//        System.out.println(selectOperator);//        System.out.println(secondNumberString);        //数据校验,必须是数字字符串        String regex = "\\d+";        //校验第一个数        if (!firstNumberString.matches(regex)) {//            System.out.println("数据不匹配");            //public static void showMessageDialog(Component parentComponent,Object message)            JOptionPane.showMessageDialog(this, "第一个操作数不满足要求必须是数字");            this.firstNumber.setText("");            this.firstNumber.requestFocus();            return;//回去吧        }        if (!secondNumberString.matches(regex)) {//            System.out.println("数据不匹配");            //public static void showMessageDialog(Component parentComponent,Object message)            JOptionPane.showMessageDialog(this, "第二个操作数不满足要求必须是数字");             this.secondNumber.setText("");            this.secondNumber.requestFocus();            return;//回去吧        }        //把字符串数据转换为整数        int firstNumber = Integer.parseInt(firstNumberString);        int secondNumber = Integer.parseInt(secondNumberString);        //定义变量接收结果        int resultNumber = 0;        switch (selectOperator) {            case "+":                resultNumber = firstNumber + secondNumber;                break;            case "-":                resultNumber = firstNumber - secondNumber;                break;            case "*":                resultNumber = firstNumber * secondNumber;                break;            case "/":                if(secondNumber==0){                     JOptionPane.showMessageDialog(this, "除数不能为0");                     this.secondNumber.setText("");                     this.secondNumber.requestFocus();                     return;                }else {                                        resultNumber = firstNumber / secondNumber;                }                break;        }        //把结果赋值给结果框        this.resultNumber.setText(String.valueOf(resultNumber));    }//GEN-LAST:event_jButton1ActionPerformed    /**     * @param args the command line arguments     *///    public static void main(String args[]) {//        /* Create and display the form *///        java.awt.EventQueue.invokeLater(new Runnable() {//            public void run() {//                new NewJFrame().setVisible(true);//            }//        });//    }    // Variables declaration - do not modify//GEN-BEGIN:variables    private javax.swing.JTextField firstNumber;    private javax.swing.JButton jButton1;    private javax.swing.JLabel jLabel1;    private javax.swing.JLabel jLabel2;    private javax.swing.JLabel jLabel3;    private javax.swing.JLabel jLabel4;    private javax.swing.JTextField resultNumber;    private javax.swing.JTextField secondNumber;    private javax.swing.JComboBox selectOperator;    // End of variables declaration//GEN-END:variables}


a:修改图标
b:设置皮肤

c:设置居中

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package cn.itcast.util;import java.awt.Dimension;import java.awt.Image;import java.awt.Toolkit;import javax.swing.JFrame;/** * 专门做界面效果的类 * * @author Administrator */public class UiUtil {    private UiUtil() {    }    //修改窗体的图标    public static void setFrameImage(JFrame jf) {        //获取工具类对象        //public static Toolkit getDefaultToolkit():获取默认工具包。         Toolkit tk = Toolkit.getDefaultToolkit();        //根据路径获取图片        Image i = tk.getImage("src\\cn\\itcast\\resource\\user.jpg");        //给窗体设置图片        jf.setIconImage(i);    }            public static void setFrameImage(JFrame jf,String imageName) {        //获取工具类对象        //public static Toolkit getDefaultToolkit():获取默认工具包。         Toolkit tk = Toolkit.getDefaultToolkit();        //根据路径获取图片        Image i = tk.getImage("src\\cn\\itcast\\resource\\"+imageName);        //给窗体设置图片        jf.setIconImage(i);    }    //设置窗体居中    public static void setFrameCenter(JFrame jf) {        /*         思路:         A:获取屏幕的宽和高         B:获取窗体的宽和高         C:(用屏幕的宽-窗体的宽)/2,(用屏幕的高-窗体的高)/2作为窗体的新坐标。         */        //获取工具对象        Toolkit tk = Toolkit.getDefaultToolkit();        //获取屏幕的宽和高        Dimension d = tk.getScreenSize();        double srceenWidth = d.getWidth();        double srceenHeigth = d.getHeight();        //获取窗体的宽和高        int frameWidth = jf.getWidth();        int frameHeight = jf.getHeight();        //获取新的宽和高        int width = (int) (srceenWidth - frameWidth) / 2;        int height = (int) (srceenHeigth - frameHeight) / 2;        //设置窗体坐标        jf.setLocation(width, height);    }}


d:数据校验

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package cn.itcast.view;import cn.itcast.dao.UserDao;import cn.itcast.dao.impl.UserDaoImpl;import cn.itcast.util.UiUtil;import javax.swing.JOptionPane;/** * * @author Administrator */public class LoginFrame extends javax.swing.JFrame {    /**     * Creates new form LoginFrame     */    public LoginFrame() {        initComponents();        init();    }    private void init() {        this.setTitle("登录界面");        this.setResizable(false);        UiUtil.setFrameCenter(this);        UiUtil.setFrameImage(this,"user.jpg");    }    /**     * This method is called from within the constructor to initialize the form.     * WARNING: Do NOT modify this code. The content of this method is always     * regenerated by the Form Editor.     */    @SuppressWarnings("unchecked")    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents    private void initComponents() {        jLabel1 = new javax.swing.JLabel();        jLabel2 = new javax.swing.JLabel();        jtfUsername = new javax.swing.JTextField();        jpfPassword = new javax.swing.JPasswordField();        jButton1 = new javax.swing.JButton();        jButton2 = new javax.swing.JButton();        jButton3 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jLabel1.setText("用户名:");        jLabel2.setText("密码:");        jButton1.setText("登录");        jButton1.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton1ActionPerformed(evt);            }        });        jButton2.setText("重置");        jButton2.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton2ActionPerformed(evt);            }        });        jButton3.setText("注册");        jButton3.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton3ActionPerformed(evt);            }        });        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                    .addGroup(layout.createSequentialGroup()                        .addGap(42, 42, 42)                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                            .addComponent(jLabel1)                            .addComponent(jLabel2))                        .addGap(18, 18, 18)                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                            .addComponent(jtfUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)                            .addComponent(jpfPassword)))                    .addGroup(layout.createSequentialGroup()                        .addGap(64, 64, 64)                        .addComponent(jButton1)                        .addGap(18, 18, 18)                        .addComponent(jButton2)                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)                        .addComponent(jButton3)))                .addContainerGap(61, Short.MAX_VALUE))        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGap(47, 47, 47)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel1)                    .addComponent(jtfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(31, 31, 31)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel2)                    .addComponent(jpfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(54, 54, 54)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jButton1)                    .addComponent(jButton2)                    .addComponent(jButton3))                .addContainerGap(48, Short.MAX_VALUE))        );        pack();    }// </editor-fold>//GEN-END:initComponents    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed        RegistFrame rf = new RegistFrame();        rf.setVisible(true);//        this.setVisible(false);        this.dispose();    }//GEN-LAST:event_jButton3ActionPerformed    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed        this.jtfUsername.setText("");        this.jpfPassword.setText("");    }//GEN-LAST:event_jButton2ActionPerformed    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed        /*        思路:        A:获取用户名和密码        B:正则表达式校验用户名和密码        C:创建对象调用功能,返回一个boolean值        D:根据boolean值给出提示        */          //获取用户名和密码        String username = this.jtfUsername.getText().trim();        String password = this.jpfPassword.getText().trim();                //用正则表达式做数据校验        //定义规则        //用户名规则        String usernameRegex = "[a-zA-z]{5}";        //密码规则        String passwordRegex = "\\w{6,12}";                //校验        if(!username.matches(usernameRegex)) {            JOptionPane.showMessageDialog(this, "用户名不满足条件(5个英文字母组成)");            this.jtfUsername.setText("");            this.jtfUsername.requestFocus();            return;        }                 if(!password.matches(passwordRegex)) {            JOptionPane.showMessageDialog(this, "密码不满足条件(6-12个任意单词字符)");            this.jpfPassword.setText("");            this.jpfPassword.requestFocus();            return;        }                  //创建对象调用功能,返回一个boolean值         UserDao ud = new UserDaoImpl();         boolean flag =  ud.login(username, password);                  if(flag){              JOptionPane.showMessageDialog(this, "恭喜你登录成功");//              NewJFrame njf = new NewJFrame();              NewJFrame njf = new NewJFrame(username);              njf.setVisible(true);              this.dispose();         }else {               JOptionPane.showMessageDialog(this, "用户名或者密码有误");               this.jtfUsername.setText("");               this.jpfPassword.setText("");               this.jtfUsername.requestFocus();         }    }//GEN-LAST:event_jButton1ActionPerformed    /**     * @param args the command line arguments     */    public static void main(String args[]) {        /* Set the Nimbus look and feel */        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html          */        try {            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {                if ("Nimbus".equals(info.getName())) {                    javax.swing.UIManager.setLookAndFeel(info.getClassName());                    break;                }            }        } catch (ClassNotFoundException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (InstantiationException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (IllegalAccessException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (javax.swing.UnsupportedLookAndFeelException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        }        //</editor-fold>        /* Create and display the form */        java.awt.EventQueue.invokeLater(new Runnable() {            public void run() {                new LoginFrame().setVisible(true);            }        });    }    // Variables declaration - do not modify//GEN-BEGIN:variables    private javax.swing.JButton jButton1;    private javax.swing.JButton jButton2;    private javax.swing.JButton jButton3;    private javax.swing.JLabel jLabel1;    private javax.swing.JLabel jLabel2;    private javax.swing.JPasswordField jpfPassword;    private javax.swing.JTextField jtfUsername;    // End of variables declaration//GEN-END:variables}


B:登录注册

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package cn.itcast.view;import cn.itcast.dao.UserDao;import cn.itcast.dao.impl.UserDaoImpl;import cn.itcast.util.UiUtil;import javax.swing.JOptionPane;/** * * @author Administrator */public class LoginFrame extends javax.swing.JFrame {    /**     * Creates new form LoginFrame     */    public LoginFrame() {        initComponents();        init();    }    private void init() {        this.setTitle("登录界面");        this.setResizable(false);        UiUtil.setFrameCenter(this);        UiUtil.setFrameImage(this,"user.jpg");    }    /**     * This method is called from within the constructor to initialize the form.     * WARNING: Do NOT modify this code. The content of this method is always     * regenerated by the Form Editor.     */    @SuppressWarnings("unchecked")    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents    private void initComponents() {        jLabel1 = new javax.swing.JLabel();        jLabel2 = new javax.swing.JLabel();        jtfUsername = new javax.swing.JTextField();        jpfPassword = new javax.swing.JPasswordField();        jButton1 = new javax.swing.JButton();        jButton2 = new javax.swing.JButton();        jButton3 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jLabel1.setText("用户名:");        jLabel2.setText("密码:");        jButton1.setText("登录");        jButton1.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton1ActionPerformed(evt);            }        });        jButton2.setText("重置");        jButton2.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton2ActionPerformed(evt);            }        });        jButton3.setText("注册");        jButton3.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton3ActionPerformed(evt);            }        });        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                    .addGroup(layout.createSequentialGroup()                        .addGap(42, 42, 42)                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                            .addComponent(jLabel1)                            .addComponent(jLabel2))                        .addGap(18, 18, 18)                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                            .addComponent(jtfUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)                            .addComponent(jpfPassword)))                    .addGroup(layout.createSequentialGroup()                        .addGap(64, 64, 64)                        .addComponent(jButton1)                        .addGap(18, 18, 18)                        .addComponent(jButton2)                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)                        .addComponent(jButton3)))                .addContainerGap(61, Short.MAX_VALUE))        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGap(47, 47, 47)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel1)                    .addComponent(jtfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(31, 31, 31)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel2)                    .addComponent(jpfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(54, 54, 54)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jButton1)                    .addComponent(jButton2)                    .addComponent(jButton3))                .addContainerGap(48, Short.MAX_VALUE))        );        pack();    }// </editor-fold>//GEN-END:initComponents    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed        RegistFrame rf = new RegistFrame();        rf.setVisible(true);//        this.setVisible(false);        this.dispose();    }//GEN-LAST:event_jButton3ActionPerformed    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed        this.jtfUsername.setText("");        this.jpfPassword.setText("");    }//GEN-LAST:event_jButton2ActionPerformed    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed        /*        思路:        A:获取用户名和密码        B:正则表达式校验用户名和密码        C:创建对象调用功能,返回一个boolean值        D:根据boolean值给出提示        */          //获取用户名和密码        String username = this.jtfUsername.getText().trim();        String password = this.jpfPassword.getText().trim();                //用正则表达式做数据校验        //定义规则        //用户名规则        String usernameRegex = "[a-zA-z]{5}";        //密码规则        String passwordRegex = "\\w{6,12}";                //校验        if(!username.matches(usernameRegex)) {            JOptionPane.showMessageDialog(this, "用户名不满足条件(5个英文字母组成)");            this.jtfUsername.setText("");            this.jtfUsername.requestFocus();            return;        }                 if(!password.matches(passwordRegex)) {            JOptionPane.showMessageDialog(this, "密码不满足条件(6-12个任意单词字符)");            this.jpfPassword.setText("");            this.jpfPassword.requestFocus();            return;        }                  //创建对象调用功能,返回一个boolean值         UserDao ud = new UserDaoImpl();         boolean flag =  ud.login(username, password);                  if(flag){              JOptionPane.showMessageDialog(this, "恭喜你登录成功");//              NewJFrame njf = new NewJFrame();              NewJFrame njf = new NewJFrame(username);              njf.setVisible(true);              this.dispose();         }else {               JOptionPane.showMessageDialog(this, "用户名或者密码有误");               this.jtfUsername.setText("");               this.jpfPassword.setText("");               this.jtfUsername.requestFocus();         }    }//GEN-LAST:event_jButton1ActionPerformed    /**     * @param args the command line arguments     */    public static void main(String args[]) {        /* Set the Nimbus look and feel */        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html          */        try {            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {                if ("Nimbus".equals(info.getName())) {                    javax.swing.UIManager.setLookAndFeel(info.getClassName());                    break;                }            }        } catch (ClassNotFoundException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (InstantiationException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (IllegalAccessException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (javax.swing.UnsupportedLookAndFeelException ex) {            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        }        //</editor-fold>        /* Create and display the form */        java.awt.EventQueue.invokeLater(new Runnable() {            public void run() {                new LoginFrame().setVisible(true);            }        });    }    // Variables declaration - do not modify//GEN-BEGIN:variables    private javax.swing.JButton jButton1;    private javax.swing.JButton jButton2;    private javax.swing.JButton jButton3;    private javax.swing.JLabel jLabel1;    private javax.swing.JLabel jLabel2;    private javax.swing.JPasswordField jpfPassword;    private javax.swing.JTextField jtfUsername;    // End of variables declaration//GEN-END:variables}

注册

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package cn.itcast.view;import cn.itcast.dao.UserDao;import cn.itcast.dao.impl.UserDaoImpl;import cn.itcast.pojo.User;import cn.itcast.util.UiUtil;import javax.swing.JOptionPane;/** * * @author Administrator */public class RegistFrame extends javax.swing.JFrame {    /**     * Creates new form LoginFrame     */    public RegistFrame() {        initComponents();        init();    }        private void init() {        this.setTitle("注册界面");        this.setResizable(false);        UiUtil.setFrameCenter(this);        UiUtil.setFrameImage(this,"user.jpg");    }    /**     * This method is called from within the constructor to initialize the form.     * WARNING: Do NOT modify this code. The content of this method is always     * regenerated by the Form Editor.     */    @SuppressWarnings("unchecked")    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents    private void initComponents() {        jLabel1 = new javax.swing.JLabel();        jLabel2 = new javax.swing.JLabel();        jtfUsername = new javax.swing.JTextField();        jpfPassword = new javax.swing.JPasswordField();        jButton1 = new javax.swing.JButton();        jButton3 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jLabel1.setText("用户名:");        jLabel2.setText("密码:");        jButton1.setText("取消");        jButton1.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton1ActionPerformed(evt);            }        });        jButton3.setText("注册");        jButton3.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton3ActionPerformed(evt);            }        });        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGap(42, 42, 42)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                    .addGroup(layout.createSequentialGroup()                        .addComponent(jButton3)                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)                        .addComponent(jButton1)                        .addGap(72, 72, 72))                    .addGroup(layout.createSequentialGroup()                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                            .addComponent(jLabel1)                            .addComponent(jLabel2))                        .addGap(18, 18, 18)                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                            .addComponent(jtfUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)                            .addComponent(jpfPassword))                        .addContainerGap(61, Short.MAX_VALUE))))        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGap(47, 47, 47)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel1)                    .addComponent(jtfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(31, 31, 31)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jLabel2)                    .addComponent(jpfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(jButton3)                    .addComponent(jButton1))                .addGap(50, 50, 50))        );        pack();    }// </editor-fold>//GEN-END:initComponents    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed       goLogin();    }//GEN-LAST:event_jButton1ActionPerformed    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed        /*        分析:        A:获取用户名和密码        B:用正则表达式做数据校验        C:封装成用户对象        D:调用用户操作的功能进行注册        E:回到登录界面        */        //获取用户名和密码        String username = this.jtfUsername.getText().trim();        String password = this.jpfPassword.getText().trim();                //用正则表达式做数据校验        //定义规则        //用户名规则        String usernameRegex = "[a-zA-z]{5}";        //密码规则        String passwordRegex = "\\w{6,12}";                //校验        if(!username.matches(usernameRegex)) {            JOptionPane.showMessageDialog(this, "用户名不满足条件(5个英文字母组成)");            this.jtfUsername.setText("");            this.jtfUsername.requestFocus();            return;        }                 if(!password.matches(passwordRegex)) {            JOptionPane.showMessageDialog(this, "密码不满足条件(6-12个任意单词字符)");            this.jpfPassword.setText("");            this.jpfPassword.requestFocus();            return;        }                  //封装成用户对象         User user = new User();         user.setUsername(username);         user.setPassword(password);                  //调用用户操作的功能进行注册         UserDao ud = new UserDaoImpl();         ud.regist(user);                  //给出提示          JOptionPane.showMessageDialog(this, "用户注册成功,回到登录界面");                    goLogin();    }//GEN-LAST:event_jButton3ActionPerformed    private void goLogin() {        LoginFrame lf = new LoginFrame();       lf.setVisible(true);       this.dispose();    }        /**     * @param args the command line arguments     *///    public static void main(String args[]) {//        /* Set the Nimbus look and feel *///        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html //         *///        try {//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {//                if ("Nimbus".equals(info.getName())) {//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());//                    break;//                }//            }//        } catch (ClassNotFoundException ex) {//            java.util.logging.Logger.getLogger(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);//        } catch (InstantiationException ex) {//            java.util.logging.Logger.getLogger(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);//        } catch (IllegalAccessException ex) {//            java.util.logging.Logger.getLogger(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {//            java.util.logging.Logger.getLogger(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);//        }//        //</editor-fold>////        /* Create and display the form *///        java.awt.EventQueue.invokeLater(new Runnable() {//            public void run() {//                new RegistFrame().setVisible(true);//            }//        });//    }    // Variables declaration - do not modify//GEN-BEGIN:variables    private javax.swing.JButton jButton1;    private javax.swing.JButton jButton3;    private javax.swing.JLabel jLabel1;    private javax.swing.JLabel jLabel2;    private javax.swing.JPasswordField jpfPassword;    private javax.swing.JTextField jtfUsername;    // End of variables declaration//GEN-END:variables}




0 0