在java中,设计登陆界面如下图所示,为“登陆”和“取消”按钮编写单击事件处理代码,使得单击“登录”按钮时,检查用户名和密码是否都输入了,如果都输入了则把信息显示在上方标签,如果未全输入则在上方标签上显示“请输入用户名和密码”;单击“取消”按钮时,将姓名和密码输入框内容清空,同时将上方标签文本改为“用户登录” 。
时间: 2024-03-17 14:42:12 浏览: 25
好的,以下是 Java Swing 的代码实现:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame {
private JLabel label;
private JTextField textField;
private JPasswordField passwordField;
public LoginFrame() {
setTitle("用户登录");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 5, 5));
getContentPane().add(panel, BorderLayout.CENTER);
JLabel label1 = new JLabel("用户名:");
panel.add(label1);
textField = new JTextField();
panel.add(textField);
JLabel label2 = new JLabel("密码:");
panel.add(label2);
passwordField = new JPasswordField();
panel.add(passwordField);
JButton button1 = new JButton("登录");
button1.addActionListener(new LoginListener());
panel.add(button1);
JButton button2 = new JButton("取消");
button2.addActionListener(new CancelListener());
panel.add(button2);
label = new JLabel("用户登录", JLabel.CENTER);
getContentPane().add(label, BorderLayout.NORTH);
}
private class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String username = textField.getText();
String password = new String(passwordField.getPassword());
if (username.isEmpty() || password.isEmpty()) {
label.setText("请输入用户名和密码");
} else {
label.setText("用户名:" + username + ",密码:" + password);
}
}
}
private class CancelListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
textField.setText("");
passwordField.setText("");
label.setText("用户登录");
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setVisible(true);
}
}
```
您可以将代码复制到 Java IDE 中运行,查看效果。
相关推荐
![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)