java语言实现用户注册和登录

2022-04-02 科技 108阅读
//这个是我写的,里面有连接数据库的部分。你可以拿去参考一下
importjava.awt.*;
importjavax.swing.*;

importjava.awt.event.*;
importjava.sql.*;

classLoginFrmextendsJFrameimplementsActionListener//throwsException
{
JLabellbl1=newJLabel("用户名:");
JLabellbl2=newJLabel("密码:");
JTextFieldtxt=newJTextField(5);
JPasswordFieldpf=newJPasswordField();
JButtonbtn1=newJButton("确定");
JButtonbtn2=newJButton("取消");

publicLoginFrm(){
this.setTitle("登陆");
JPaneljp=(JPanel)this.getContentPane();
jp.setLayout(newGridLayout(3,2,5,5));
jp.add(lbl1);
jp.add(txt);
jp.add(lbl2);
jp.add(pf);
jp.add(btn1);
jp.add(btn2);
btn1.addActionListener(this);
btn2.addActionListener(this);
}

publicvoidactionPerformed(ActionEventae){
if(ae.getSource()==btn1){
try{
Class.forName("com.mysql.jdbc.Driver");//mysql数据库
Connectioncon=DriverManager.getConnection(
"jdbc:mysql://localhost/Car_zl","root","1");//数据库名为Car_zl,密码为1
System.out.println("com:"+con);
Statementcmd=con.createStatement();
Stringsql="select*fromuserwhereUser_ID='"
+txt.getText()+"'andUser_ps='"
+pf.getText()+"'";
ResultSetrs=cmd
.executeQuery(sql);//表名为user,user_ID和User_ps是存放用户名和密码的字段名

if(rs.next()){
JOptionPane.showMessageDialog(null,"登陆成功!");
}else
JOptionPane.showMessageDialog(null,"用户名或密码错误!");
}catch(Exceptionex){

}

if(ae.getSource()==btn2){
System.out.println("1111111111111");
//txt.setText("");
//pf.setText("");
System.exit(0);
}
}
}

publicstaticvoidmain(Stringarg[]){
JFrame.setDefaultLookAndFeelDecorated(true);
LoginFrmfrm=newLoginFrm();
frm.setSize(400,200);
frm.setVisible(true);
}
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com