请你帮我写一个用户登陆界面Java代码
时间: 2023-08-28 13:24:19 浏览: 45
好的,以下是一个简单的Java用户登录界面代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserLogin extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
public UserLogin() {
// 设置窗口标题
setTitle("User Login");
// 创建面板和布局
JPanel panel = new JPanel(new GridLayout(3, 2));
// 添加标签和文本框
panel.add(new JLabel("Username:"));
usernameField = new JTextField();
panel.add(usernameField);
panel.add(new JLabel("Password:"));
passwordField = new JPasswordField();
panel.add(passwordField);
// 添加登录按钮
JButton loginButton = new JButton("Login");
loginButton.addActionListener(this);
panel.add(loginButton);
// 添加取消按钮
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
panel.add(cancelButton);
// 添加面板到窗口
add(panel);
// 设置窗口大小和位置
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (e.getActionCommand().equals("Login")) {
if (username.equals("admin") && password.equals("123456")) {
JOptionPane.showMessageDialog(this, "Login successful!");
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password!");
}
} else if (e.getActionCommand().equals("Cancel")) {
System.exit(0);
}
}
public static void main(String[] args) {
new UserLogin();
}
}
```
在这个示例中,我们创建了一个继承自JFrame的UserLogin类,实现了ActionListener接口。在构造函数中,我们创建了一个面板和一个GridLayout布局,并添加了标签、文本框和两个按钮。当用户单击“Login”按钮时,我们检查用户名和密码是否匹配,如果匹配,显示一个消息框,否则显示另一个消息框。当用户单击“Cancel”按钮时,我们退出应用程序。最后,在main()方法中,我们实例化UserLogin类,以显示用户登录界面。