点击确定后如果用户名为"zhangsan",密码为“123”则弹出信息:“欢迎使用”,否则弹出信息“用户名和密码错误,请重新输入”,点击取消则关闭窗口,退出程序
时间: 2024-03-21 11:40:47 浏览: 21
好的,根据你的需求,以下是一个简单的Java Swing用户登录示例代码,可以帮助你实现上述功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
public LoginFrame() {
setTitle("用户登录");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
JLabel usernameLabel = new JLabel("用户名:");
panel.add(usernameLabel);
usernameField = new JTextField();
panel.add(usernameField);
JLabel passwordLabel = new JLabel("密 码:");
panel.add(passwordLabel);
passwordField = new JPasswordField();
panel.add(passwordField);
JButton okButton = new JButton("确定");
okButton.addActionListener(this);
panel.add(okButton);
JButton cancelButton = new JButton("取消");
cancelButton.addActionListener(this);
panel.add(cancelButton);
add(panel);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("确定")) {
String username = usernameField.getText().trim();
String password = new String(passwordField.getPassword());
if (username.equals("zhangsan") && password.equals("123")) {
JOptionPane.showMessageDialog(this, "欢迎使用");
dispose();
} else {
JOptionPane.showMessageDialog(this, "用户名和密码错误,请重新输入");
usernameField.setText("");
passwordField.setText("");
}
} else if (e.getActionCommand().equals("取消")) {
dispose();
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
在这个示例中,我们创建了一个名为`LoginFrame`的Java Swing窗口,并添加了用户名和密码输入框、确定按钮和取消按钮等组件。当用户点击确定按钮时,程序会获取用户名和密码输入框中的值,并与预设的“zhangsan”和“123”进行比较。如果匹配成功,程序会弹出“欢迎使用”消息框并关闭窗口;否则,程序会弹出“用户名和密码错误,请重新输入”消息框并清空用户名和密码输入框中的值。如果用户点击取消按钮,则程序会直接关闭窗口并退出。
希望这个示例能够帮助你实现你的需求。如果你有任何问题,请随时问我。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)