import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class UserLogin extends JFrame implements ActionListener{
   	JLabel lblUserName;
	JLabel lblUserPwd;
	JTextField txtUsrName;
	JPasswordField txtUsrPwd;
	JButton btnRegister;
	JButton btnCancel;
    public UserLogin () {
    	this.setTitle("用户注册"); //set the title		
	    JPanel panel1=new JPanel();
	 	panel1.setLayout(new FlowLayout());
		lblUserName=new JLabel("用户名：");
		panel1.add(lblUserName);
		txtUsrName=new JTextField(20);
		panel1.add(txtUsrName);	
	    JPanel panel2=new JPanel();
	 	panel2.setLayout(new FlowLayout());
		lblUserPwd=new JLabel("密   码：");
		panel2.add(lblUserPwd);
		txtUsrPwd=new JPasswordField(20);
		txtUsrPwd.setEchoChar('*');
		panel2.add(txtUsrPwd);
		JPanel btnPanel=new JPanel();
		btnRegister=new JButton("注册");
		btnPanel.add(btnRegister);
		btnCancel=new JButton("取消");
		btnPanel.add(btnCancel);						
	    Container c=this.getContentPane();
	    c.setLayout(new BorderLayout());	    
		c.add(panel1,BorderLayout.NORTH);
		c.add(panel2,BorderLayout.CENTER);
		c.add(btnPanel,BorderLayout.SOUTH);		
		btnRegister.addActionListener(this);
		btnCancel.addActionListener(this);  		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocation(300,200);
		this.pack();
		this.setResizable(false); 	
		this.setVisible(true); 
    }
    public void actionPerformed(ActionEvent e){
	   	if(e.getSource()==btnRegister){                        //如果按了注册按钮
DataBaseManager db=new DataBaseManager();
		      String userName=txtUsrName.getText().trim();
		      char pwd[]=txtUsrPwd.getPassword();
		      String password=new String(pwd);
		      password=password.trim();
		      if(userName.equals("")||password.equals("")){    //用户名为空或口令为空
			      System.out.println(userName.trim());
                    JOptionPane.showMessageDialog(null,"用户名或密码不能为空!","Message",
JOptionPane.DEFAULT_OPTION);
			      return;
		      }
		      String sql="select * from user_table where username="+"'"+userName+"'";
		      System.out.println(sql);
		      ResultSet rs=db.getResult(sql);
		      try{
			      if(rs.next()){	    //数据库中已经存在了该用户名		      	
JOptionPane.showMessageDialog(null," 该用户已存在，请重新注册！",
"Message",JOptionPane.DEFAULT_OPTION);
			      }		     	 	
			      else {               //数据库中不存在此用户，则把用户加入到数据库中
			      sql="insert into user_table values ("+"'"+userName+"'"+",'"+password+"')";
			      	db.updateSql(sql);
			      	System.out.println(sql);
JOptionPane.showMessageDialog(null," 恭喜你，注册成功！","Message",
JOptionPane.DEFAULT_OPTION);
			      }
		      }
		      catch(Exception ee){
		      	System.out.println(ee.getMessage());
		      }
		      finally{
		      	db.closeConnection();
		      }
	   	}
	   	else if(e.getSource()==btnCancel){      //如果按了取消按钮
	   		this.dispose();
	   	}
	}
	public static void main(String args[]){
		new UserLogin ();
	}
}