用java编写登录界面
时间: 2023-11-26 11:06:30 浏览: 29
好的,下面是一个简单的Java登录界面示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel usernameLabel;
private JLabel passwordLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
private JButton cancelButton;
public LoginFrame() {
setTitle("登录");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(3, 2));
usernameLabel = new JLabel("用户名:");
usernameField = new JTextField();
passwordLabel = new JLabel("密码:");
passwordField = new JPasswordField();
loginButton = new JButton("登录");
cancelButton = new JButton("取消");
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(loginButton);
panel.add(cancelButton);
add(panel);
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("123456")) {
JOptionPane.showMessageDialog(this, "登录成功!");
dispose();
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
}
} else if (e.getSource() == cancelButton) {
dispose();
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
这个登录界面包含两个文本框和两个按钮,用户输入用户名和密码后,点击登录按钮,如果用户名和密码正确,就弹出一个提示框显示登录成功,关闭登录界面;如果用户名或密码错误,就弹出一个提示框告诉用户。如果点击取消按钮,就关闭登录界面。