帮我用java写个登录页面
时间: 2024-02-11 10:07:21 浏览: 15
好的,以下是一个简单的Java登录页面示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login extends JFrame implements ActionListener {
private JLabel titleLabel, usernameLabel, passwordLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton, cancelButton;
public Login() {
// 设置窗口标题
setTitle("Login Page");
// 设置窗口大小
setSize(400, 300);
// 设置窗口布局
setLayout(new GridLayout(4, 2));
// 添加标题标签
titleLabel = new JLabel("Please enter your login credentials:");
add(titleLabel);
// 添加用户名标签和文本框
usernameLabel = new JLabel("Username:");
add(usernameLabel);
usernameField = new JTextField();
add(usernameField);
// 添加密码标签和文本框
passwordLabel = new JLabel("Password:");
add(passwordLabel);
passwordField = new JPasswordField();
add(passwordField);
// 添加登录和取消按钮
loginButton = new JButton("Login");
loginButton.addActionListener(this);
add(loginButton);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
add(cancelButton);
// 显示窗口
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// 检查用户名和密码是否正确
if (username.equals("admin") && password.equals("password")) {
JOptionPane.showMessageDialog(this, "Login successful!");
} else {
JOptionPane.showMessageDialog(this, "Incorrect username or password.");
}
} else if (e.getSource() == cancelButton) {
// 关闭窗口
dispose();
}
}
public static void main(String[] args) {
new Login();
}
}
```
这个Java登录页面使用了Swing GUI库来创建窗口和组件。当用户点击“Login”按钮时,程序将获取用户名和密码文本框中的文本,并将其与预定义的用户名和密码进行比较。如果用户名和密码正确,则会显示“Login successful!”消息框,否则将显示“Incorrect username or password.”消息框。当用户点击“Cancel”按钮时,程序将关闭窗口。