值无法解析java中的错误

时间:2017-04-05 08:59:15

标签: java string scope

我收到错误"价值无法解决"当我用密码字段进行字符串检查时。任何人都可以告诉我的代码有什么问题。它显示了我已声明我的字符串变量"传递"的错误。我的代码如下

public class PassWord implements ActionListener {
    JButton b;
    PassWord() {
        JFrame f=new JFrame("Home"); 
        JPasswordField passwd = new JPasswordField();
        JLabel l1=new JLabel("Enter Password");  
        l1.setBounds(625,310, 150,30); 
        passwd.setBounds(600,340,150,30);
         b = new JButton("Login");
         b.setBounds(640,380,70,30);
         b.addActionListener(this); 


         f.add(passwd); f.add(l1); f.add(b);
         f.setSize(1280,720);
         f.setLayout(null);    
             f.setVisible(true);          
    }

    public void actionPerformed(ActionEvent e) {    
        String pass =  passwd.getPassword();
        if(pass.equals("test")) {
        System.out.println("Success");
        }
     }
}

2 个答案:

答案 0 :(得分:2)

你得到的错误:

  

passwd无法解析

是因为您需要将 JPasswordField passwd 声明为类成员,因此仅在构造函数中声明它,因此在方法 actionPerformed

答案 1 :(得分:0)

您的代码中存在两个问题。

首先,您必须将JPasswordField设为类变量: 第二:passwd.getPassword()返回一个字符数组,而不是字符串:

public class PassWord  implements ActionListener {
    JButton b;
    JPasswordField passwd;
    PassWord() {
        JFrame f=new JFrame("Home"); 
        passwd = new JPasswordField();
        JLabel l1=new JLabel("Enter Password");  
        l1.setBounds(625,310, 150,30); 
        passwd.setBounds(600,340,150,30);
         b = new JButton("Login");
         b.setBounds(640,380,70,30);
         b.addActionListener(this); 


         f.add(passwd); f.add(l1); f.add(b);
         f.setSize(1280,720);
         f.setLayout(null);    
             f.setVisible(true);          
    }

    public void actionPerformed(ActionEvent e) {    
        char[] pass =  passwd.getPassword();
        if("test".equals(String.valueOf(pass))) {
        System.out.println("Success");
        }
     }

}