0

I'm relatively new to Java and I am trying to make a login page for my desktop application. I have a thread called "listen" that should be called when the application first opens, its job is to check weather the username and password fields are not blank.

public class Login extends JFrame implements Runnable {
    private JPanel contentPane;
    private JTextField txtUsername;
    private JPasswordField pwdPassword;
    private JLabel lblUsername;
    private JButton btnLogin;
    private JLabel lblPassword;
    private JCheckBox cboxRemember;
    private Thread run, listen;
    private boolean running = true;

public Login() {
    createWindow();
    run = new Thread(this, "Running");
    running = true;
    run.start();    
}

private void createWindow() {
     //application layout and actionListener for login button
}

public void run() {
    listen();

}

public void listen() {
    listen = new Thread("Listen") {
        public void run() {
            while (running) {
                if (txtUsername.getText().equals("") || pwdPassword.getText().equals("")) btnLogin.setEnabled(false);
                else btnLogin.setEnabled(true);
            }
        }
    };
    listen.start();
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Login frame = new Login();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
  }
}

Whenever i try to execute my code the 'listen' thread throws a NullPointerException on this line if (txtUsername.getText().equals("") || pwdPassword.getText().equals("")) btnLogin.setEnabled(false); I'm not sure what am I doing wrong, any help will be appreciated, thanks.

Dan Hayes
  • 97
  • 12
  • Your `txtUsername` and `pwdPassword` JTextField's are empty when the application starts. – CubeJockey Aug 28 '15 at 17:33
  • 1
    you will gt a NPE if txtUsername.getText() returns null ..... add a check for that and it should be the first check. Something like (txtUsername.getText()!=null && (txtUsername.getText().equals("") || pwdPassword.getText().equals(""))). Ohh and @Trobbins mentioned , the same goes for pwdPassword field too :) – digidude Aug 28 '15 at 17:33
  • 1
    When do you assign a value to `txtUsername`? It's clearly not got one (except `null`). – bcsb1001 Aug 28 '15 at 17:34

3 Answers3

1

Initialize your txtUserName and pwdPassword:

 txtUsername = new JTextField();
 pwdPassword = new JPasswordField();

Hope this helps.

Actiwitty
  • 1,232
  • 2
  • 12
  • 20
0

I think you're if{} block gets executed before any initialization. Add

if (txtUsername.getText()!=null &&( txtUsername.getText().equals("") || pwdPassword.getText().equals("")))
Jerry
  • 410
  • 6
  • 17
0

Since txtUsername and pwdPassword have not been initialized, you will get a NPE in your IF{} statement.

Sterls
  • 723
  • 12
  • 22