用java写一个登陆界面
时间: 2024-05-01 09:18:53 浏览: 13
好的,我可以帮你解决这个问题。基于Java语言的登陆界面可以使用JFrame实现用户界面,使用JDBC连接数据库进行用户认证和授权。以下是Java代码示例,希望能帮到你:
```
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class Login extends JFrame implements ActionListener {
private JLabel label1, label2;
private JTextField field;
private JPasswordField passwordField;
private JButton button;
public Login() {
super("用户认证");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(250, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridLayout(3, 1));
this.add(panel, BorderLayout.CENTER);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
label1 = new JLabel("用户名:");
panel1.add(label1);
field = new JTextField(15);
panel1.add(field);
panel.add(panel1);
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
label2 = new JLabel("密 码:");
panel2.add(label2);
passwordField = new JPasswordField(15);
passwordField.setEchoChar('*');
panel2.add(passwordField);
panel.add(panel2);
JPanel panel3 = new JPanel(new FlowLayout());
button = new JButton("登录");
button.addActionListener(this);
panel3.add(button);
panel.add(panel3);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String user = field.getText();
String pwd = new String(passwordField.getPassword());
if (user.length() == 0 || pwd.length() == 0) {
JOptionPane.showMessageDialog(null, "用户名或密码不能为空", "提示", JOptionPane.ERROR_MESSAGE);
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
String sql = "SELECT * FROM userinfo WHERE username = ? AND password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, user);
statement.setString(2, pwd);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "登陆成功", "提示", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误", "提示", JOptionPane.ERROR_MESSAGE);
}
rs.close();
statement.close();
connection.close();
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "未找到MySQL JDBC驱动", "提示", JOptionPane.ERROR_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "数据库连接失败", "提示", JOptionPane.ERROR_MESSAGE);
}
}
}
}
public static void main(String[] args) {
new Login();
}
}
```
这里我们使用MySQL数据库进行用户认证,如果用户名和密码输入正确,程序就给出"登陆成功"的提示,否则提示"用户名或密码错误"。当然,这个示例只是简单的演示了登陆界面的实现,你可以根据需要进行修改和完善。