登录界面java代码
时间: 2023-07-03 19:14:11 浏览: 52
好的,以下是一个简单的登录界面的 Java 代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginGUI extends JFrame implements ActionListener {
private JLabel userLabel, passLabel;
private JTextField userText;
private JPasswordField passText;
private JButton loginButton, cancelButton;
public LoginGUI() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null); // 居中显示
JPanel panel = new JPanel(new GridLayout(3, 2));
userLabel = new JLabel("Username:");
panel.add(userLabel);
userText = new JTextField();
panel.add(userText);
passLabel = new JLabel("Password:");
panel.add(passLabel);
passText = new JPasswordField();
panel.add(passText);
loginButton = new JButton("Login");
loginButton.addActionListener(this);
panel.add(loginButton);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
panel.add(cancelButton);
add(panel);
setVisible(true);
}
// 处理按钮点击事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userText.getText();
char[] password = passText.getPassword();
// 验证用户名和密码,这里只是简单判断
if (username.equals("admin") && new String(password).equals("123456")) {
JOptionPane.showMessageDialog(this, "Login successful!");
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password!");
}
} else if (e.getSource() == cancelButton) {
System.exit(0);
}
}
public static void main(String[] args) {
new LoginGUI();
}
}
```
这段代码使用了 Swing 组件来构建登录界面,包括标签、文本框、密码框和按钮。在 `actionPerformed` 方法中,处理了登录按钮和取消按钮的点击事件,分别执行验证用户名和密码以及退出程序的操作。