1. 程式人生 > >25 API-GUI(事件監聽機制,介面卡模式),Netbeans的概述和使用(模擬登陸註冊GUI版)

25 API-GUI(事件監聽機制,介面卡模式),Netbeans的概述和使用(模擬登陸註冊GUI版)

 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() {
			@Override
			public 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 {

	@Override
	public void add() {
		System.out.println("新增功能");
	}

	@Override
	public void delete() {
		System.out.println("刪除功能");
	}

	@Override
	public void update() {
		System.out.println("修改功能");
	}

	@Override
	public void find() {
		System.out.println("查詢功能");
	}

}

抽象介面卡類
public abstract class UserAdapter implements UserDao {

	@Override
	public void add() {
	}

	@Override
	public void delete() {
	}

	@Override
	public void update() {
	}

	@Override
	public void find() {
	}

}

繼承介面卡(實現介面指定功能)類
public class UserDaoImpl2 extends UserAdapter {
	@Override
	public 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
}