package com; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class UserInfo extends JFrame implements ActionListener { JLabel JPasswordField, idLabel; JTextField JPasswordField, idField; JButton submitButton; public UserInfo() { setTitle("用户信息"); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(3, 2)); idLabel = new JLabel("身份证号:"); add(idLabel); idField = new JTextField(); add(idField); JPasswordField = new JPasswordField("密码:"); add(JPasswordField); JPasswordField = new JTextField(); add(JPasswordField); submitButton = new JButton("提交"); add(submitButton); submitButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { String name = JPasswordField.getText(); String id = idField.getText(); JOptionPane.showMessageDialog(null, name + "笨蛋"); } public static void main(String[] args) { UserInfo userInfo = new UserInfo(); userInfo.setVisible(true); } }代码查错
时间: 2024-04-04 18:35:41 浏览: 16
在这段代码中,有几个问题需要解决:
1. `JPasswordField` 和 `JTextField` 的变量名重复了,需要修改其中一个。
2. `JPasswordField` 组件应该使用 `JPasswordField` 类型,不能使用 `JTextField` 类型。
3. 在 `actionPerformed` 方法中,获取密码的方式不正确。应该使用 `JPasswordField` 的 `getPassword` 方法获取密码。
4. 在弹出对话框时,字符串拼接的方式不正确,应该使用字符串格式化的方式。
根据上述问题,下面是修改后的代码:
```java
package com;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserInfo extends JFrame implements ActionListener {
JLabel idLabel, pwLabel;
JTextField idField;
JPasswordField pwField;
JButton submitButton;
public UserInfo() {
setTitle("用户信息");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
idLabel = new JLabel("身份证号:");
add(idLabel);
idField = new JTextField();
add(idField);
pwLabel = new JLabel("密码:");
add(pwLabel);
pwField = new JPasswordField();
add(pwField);
submitButton = new JButton("提交");
add(submitButton);
submitButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String id = idField.getText();
char[] pw = pwField.getPassword();
String password = new String(pw);
JOptionPane.showMessageDialog(null, String.format("身份证号:%s,密码:%s", id, password));
}
public static void main(String[] args) {
UserInfo userInfo = new UserInfo();
userInfo.setVisible(true);
}
}
```
这个程序现在可以正常运行,并且在点击提交按钮时,会弹出一个对话框,显示输入的身份证号和密码。