package text6; import text6.inquire; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class inquire1 extends JFrame implements ActionListener{ JLabel lbl_name=new JLabel("用户名"); JLabel lbl_pwd=new JLabel("密码"); JTextField txt_name=new JTextField(); JPasswordField txt_pwd=new JPasswordField(); JButton btn_ok=new JButton("登录"); JButton btn_cancel=new JButton("取消"); inquire dao=new inquire(); public inquire1() { setLayout(new GridLayout(3,2)); add(lbl_name); add(txt_name); add(lbl_pwd); add(txt_pwd); add(btn_ok); add(btn_cancel); btn_ok.addActionListener(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[]) { JFrame.setDefaultLookAndFeelDecorated(true); inquire1 frm=new inquire1(); frm.setSize(200,200); frm.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()==btn_ok) { String uname=txt_name.getText().trim(); String upwd=txt_pwd.getText().trim(); boolean flag=dao.validate(uname, upwd); if(flag) { JOptionPane.showMessageDialog(this,"用户验证通过"); }else { JOptionPane.showConfirmDialog(this,"用户名或密码输入错误"); } } } }改错
时间: 2024-03-17 20:45:27 浏览: 277
该代码没有语法错误,但是可以进行一些改进:
1. 在验证失败时,应该使用 JOptionPane.showMessageDialog() 方法显示错误信息,而不是使用 JOptionPane.showConfirmDialog() 方法,因为 showConfirmDialog() 方法会返回用户点击的按钮,而 showMessageDialog() 方法只是显示信息。
2. 在验证成功时,应该直接关闭窗口,因为没有其他操作。
3. 应该使用密码框的 getPassword() 方法获取密码,而不是 getText() 方法,因为 getPassword() 方法返回的是字符数组,更加安全。
以下是进行了改进的代码:
```java
package text6;
import text6.inquire;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class inquire1 extends JFrame implements ActionListener {
JLabel lbl_name = new JLabel("用户名");
JLabel lbl_pwd = new JLabel("密码");
JTextField txt_name = new JTextField();
JPasswordField txt_pwd = new JPasswordField();
JButton btn_ok = new JButton("登录");
JButton btn_cancel = new JButton("取消");
inquire dao = new inquire();
public inquire1() {
setLayout(new GridLayout(3, 2));
add(lbl_name);
add(txt_name);
add(lbl_pwd);
add(txt_pwd);
add(btn_ok);
add(btn_cancel);
btn_ok.addActionListener(this);
btn_cancel.addActionListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
inquire1 frm = new inquire1();
frm.setSize(200, 200);
frm.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_ok) {
String uname = txt_name.getText().trim();
String upwd = new String(txt_pwd.getPassword());
boolean flag = dao.validate(uname, upwd);
if (flag) {
JOptionPane.showMessageDialog(this, "用户验证通过");
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "用户名或密码输入错误");
}
} else if (e.getSource() == btn_cancel) {
this.dispose();
}
}
}
```
阅读全文