用javaGui写一个用户登录页面
时间: 2024-05-11 12:17:18 浏览: 13
好的,以下是用Java GUI编写用户登录页面的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login extends JFrame implements ActionListener {
JLabel userLabel, passwordLabel;
JTextField userText;
JPasswordField passwordText;
JButton loginButton, cancelButton;
Login() {
setTitle("用户登录");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
userLabel = new JLabel("用户名:");
passwordLabel = new JLabel("密码:");
userText = new JTextField(20);
passwordText = new JPasswordField(20);
loginButton = new JButton("登录");
cancelButton = new JButton("取消");
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(userLabel);
panel.add(userText);
panel.add(passwordLabel);
panel.add(passwordText);
panel.add(loginButton);
panel.add(cancelButton);
add(panel);
setVisible(true);
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userText.getText();
String password = new String(passwordText.getPassword());
if (username.equals("admin") && password.equals("123456")) {
JOptionPane.showMessageDialog(null, "登录成功!");
dispose();
// 在这里添加你要跳转的页面
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误!", "错误", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getSource() == cancelButton) {
dispose();
}
}
public static void main(String[] args) {
new Login();
}
}
```
运行该程序,将会显示一个窗口,包含用户名、密码输入框和登录、取消按钮。当用户输入正确的用户名和密码并点击登录按钮时,将会弹出一个消息框提示登录成功。如果用户名或密码不正确,则会弹出一个错误消息框。
你可以根据需要修改代码,比如更改用户名和密码、添加更多的用户输入项等等。