不论输入什么都是错误,是不是因为没有储存输入的用户名和密码,怎么改呀(•̥́_•ૅू˳)

package This;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Main {
public static void main(String[]args){
LoginDemo LD=new LoginDemo();
}
}
class LoginDemo extends JFrame{
private String username="123";
private String passkey="123";
JFrame window;
//用户名,密码
JTextField user;
JTextField pwd;
//登录按钮
JButton Login;
public LoginDemo(){
window=new JFrame("学生管理系统");
window.setSize(600,600);
window.setLocationRelativeTo(null);
window.setLayout(null);
window.setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setVisible(true);

       JLabel name =new JLabel("用户名:");
       name.setBounds(150,100,100,100);
       window.add(name);
       
       JLabel key =new JLabel("密码:");
       key.setBounds(150,150,100,100);
       window.add(key);
       
       user=new JTextField ();
       user.setBounds(200,130,300,40);
       window.add(user);
       String use=user.getText();
       
       pwd=new JPasswordField();
       pwd.setBounds(200,180,300,40);
       window.add(pwd);
       String pw=pwd.getText(); 

       Login=new JButton("登录");
       Login.setBounds(250,300,100,50);
       window.add(Login);
    //设置点击事件
    Login.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (use.equals(username)) {
                 if(pw.equals(passkey)) {
                     System.out.println("正确");
                 }
                 else {
                    System.out.println("错误"); 
                 }
              }
              else {
                System.out.println("错误");  
            
              }
        }
  });
    
    
 }
  

}

if (use.equals(username)) {
你要在这个函数的这个语句之前读取use和pw的值。因为这时候才能读取到用户输入的用户名和密码
你代码中String use=user.getText();所在的地方是控件刚创建的地方,还没有输入呢,getText得到的是个空的
这样试试:


public void actionPerformed(ActionEvent e) {
String use=user.getText();
String pw=pwd.getText();
            if (use.equals(username)) {

if (use.equals(username)) {
改为
if (user.getText().equals(username)) {
if(pw.equals(passkey)) {
改为
if(pwd.getText().equals(passkey)) {

String use = user.getText();
String pw = pwd.getText();
获取用户名密码的代码应该写在点击事件里面才能获取得到。

@点亮~黑夜 测试@功能

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632