用java创建一个有账号和密码的登录窗口
时间: 2024-03-14 20:45:06 浏览: 23
下面是一个简单的Java Swing程序,包含一个登录窗口,用户需要输入账号和密码才能登录。
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel userLabel, passwordLabel;
private JTextField userText;
private JPasswordField passwordText;
private JButton loginButton, cancelButton;
public LoginFrame() {
super("登录窗口");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // 居中显示窗口
userLabel = new JLabel("账号:");
passwordLabel = new JLabel("密码:");
userText = new JTextField(10);
passwordText = new JPasswordField(10);
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);
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String user = userText.getText();
String password = new String(passwordText.getPassword());
if (user.equals("admin") && password.equals("123456")) {
JOptionPane.showMessageDialog(null, "登录成功");
} else {
JOptionPane.showMessageDialog(null, "账号或密码错误");
}
} else if (e.getSource() == cancelButton) {
System.exit(0);
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setVisible(true);
}
}
```
运行该程序,会弹出一个登录窗口,用户需要输入账号和密码才能登录。如果账号和密码都正确,会弹出一个提示框显示“登录成功”,否则会提示“账号或密码错误”。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)