编写Java应用程序,实现使用空布局完成登陆界面设计。当用户点击界面中的“登录”按钮时,获取用户输入的用户名和密码并进行校验,如果账号密码正确,弹出另外一个窗口。如果账号密码错误弹出对话框。单击重置按钮实现账号密码清空
时间: 2024-03-16 19:41:46 浏览: 19
好的,我可以帮你解答这个问题。以下是Java代码的实现,具体注释在代码中:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
// 登录界面的组件
private JLabel nameLabel = new JLabel("用户名");
private JTextField nameField = new JTextField(20);
private JLabel pwdLabel = new JLabel("密码");
private JPasswordField pwdField = new JPasswordField(20);
private JButton loginButton = new JButton("登录");
private JButton resetButton = new JButton("重置");
// 构造函数
public LoginFrame() {
// 设置窗口标题
setTitle("登录");
// 设置窗口大小和位置
setSize(300, 200);
setLocationRelativeTo(null);
// 设置布局为空布局
setLayout(null);
// 添加组件到窗口中,并设置位置
nameLabel.setBounds(50, 30, 50, 20);
add(nameLabel);
nameField.setBounds(110, 30, 120, 20);
add(nameField);
pwdLabel.setBounds(50, 70, 50, 20);
add(pwdLabel);
pwdField.setBounds(110, 70, 120, 20);
add(pwdField);
loginButton.setBounds(50, 110, 80, 25);
add(loginButton);
resetButton.setBounds(150, 110, 80, 25);
add(resetButton);
// 添加按钮的点击事件监听器
loginButton.addActionListener(this);
resetButton.addActionListener(this);
}
// 按钮的点击事件处理函数
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) { // 点击了登录按钮
String name = nameField.getText(); // 获取用户名
String pwd = new String(pwdField.getPassword()); // 获取密码
// 模拟校验用户名和密码
if (name.equals("admin") && pwd.equals("123456")) {
JOptionPane.showMessageDialog(null, "登录成功"); // 弹出登录成功对话框
new MainFrame(); // 打开另一个窗口
dispose(); // 关闭登录窗口
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误"); // 弹出错误对话框
}
} else if (e.getSource() == resetButton) { // 点击了重置按钮
nameField.setText(""); // 清空用户名
pwdField.setText(""); // 清空密码
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
// 另一个窗口的代码
class MainFrame extends JFrame {
public MainFrame() {
// 设置窗口标题
setTitle("主界面");
// 设置窗口大小和位置
setSize(300, 200);
setLocationRelativeTo(null);
// 显示窗口
setVisible(true);
}
}
```
希望这段代码能够帮到你,如果还有其他问题欢迎继续提问。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)