0

Now I know that this is a bad approach, but I'm making a program and i need users to log in. I thought that if I created two different JFrames (one to log in, and one for my program) that I could just change their respective visibility states to decide which frame I wanted to show.

I created the login screen and when you hit login, it checks the credentials and it's supposed to hide the login screen and show the main program's screen.

I tried disposing the login screen, and changing the visibility state of the screen separately and I keep getting a null pointer Exception. The program does continue to run but I don't think it's good to proceed with this error.

I'm not sure how I could get rid of the login screen. This is a basic sketch of my program and the three classes so far:

import java.awt.EventQueue;

public class Class1 {



    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Windows window = new Windows(); // localizes the window class
                    window.dMMWindow();
                    window.displayloginWindow(); //calls for the window method inside of the window class

                } catch (Exception e) { //catches any exceptions
                    e.printStackTrace();
                }
            }
        });
    }

}

and the second class

 import java.awt.Button;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;



import org.eclipse.wb.swing.FocusTraversalOnArray;

public class Windows {

    private JFrame loginWindow;
    private JFrame ErrorWindow;
    private JFrame moneyManagerWindow;
    private JTextField inputUsername;
    private JTextField inputPassword;


    /**
     * Displays login window
     */
    public void displayloginWindow(){
        createLoginWindow();
        loginWindow.setVisible(true);
    }

    public void disposeWindow(String frameName){ //disposes specified windows
        switch (frameName){ //switch statement to close specified windows
        case "loginWindow":
            loginWindow.setVisible(false);
        break;

        case "ErrorWindow":
            ErrorWindow.setVisible(false);
        break;

        case "moneyManagerWindow":
            moneyManagerWindow.setVisible(false);
        break;

        default:

        break;

        }

    }

    public void displayErrorWindow(){
        createErrorWindow();
        ErrorWindow.setVisible(true);
    }

    public void dMMWindow(){
        createMoneyManagerWindow();
        moneyManagerWindow.setVisible(true);

    }

    private void createMoneyManagerWindow() {
        moneyManagerWindow = new JFrame();
        moneyManagerWindow.setResizable(false);
        moneyManagerWindow.setTitle("Money Manager");
        moneyManagerWindow.setBounds(100, 100, 621, 490);
        moneyManagerWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        moneyManagerWindow.setLocationRelativeTo(null);

        JTextPane welcomePane = new JTextPane();
        welcomePane.setEditable(false);
        welcomePane.setBackground(SystemColor.menu);
        welcomePane.setText("Welcome: ");
        welcomePane.setBounds(12, 13, 230, 22);
        moneyManagerWindow.getContentPane().add(welcomePane);

    }

    private void createErrorWindow() {
        ErrorWindow = new JFrame();
        ErrorWindow.setTitle("Error");
        ErrorWindow.setResizable(false);
        ErrorWindow.setBounds(100, 100, 353, 193);
        ErrorWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        ErrorWindow.setLocationRelativeTo(null);
        ErrorWindow.setAlwaysOnTop(true);

        JTextPane txtpnIncorrectUsernameOr = new JTextPane();
        txtpnIncorrectUsernameOr.setBackground(SystemColor.menu);
        txtpnIncorrectUsernameOr.setEditable(false);
        txtpnIncorrectUsernameOr.setBounds(80, 30, 207, 22);
        txtpnIncorrectUsernameOr.setText("Incorrect username or password");

        JButton contButton = new JButton("Continue");
        contButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                ErrorWindow.dispose();
            }
        });
        contButton.setBounds(127, 79, 97, 45);
        ErrorWindow.getContentPane().setLayout(null);
        ErrorWindow.getContentPane().add(txtpnIncorrectUsernameOr);
        ErrorWindow.getContentPane().add(contButton);
    }


    /**
     * Initialize the contents of the frame.
     */
    private void createLoginWindow() {
        loginWindow = new JFrame();
        loginWindow.setResizable(false);
        loginWindow.setTitle("Money Planner");
        loginWindow.setBounds(100, 100, 450, 234);
        loginWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        loginWindow.setLocationRelativeTo(null);        
        loginWindow.getContentPane().setLayout(null);
        loginWindow.isAlwaysOnTop();

        Button cAccButton = new Button("Create Account");
        cAccButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //when button is clicked
            }
        });
        cAccButton.setBounds(100, 151, 104, 24);
        loginWindow.getContentPane().add(cAccButton);

        Button loginButton = new Button("Login");
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String username = inputUsername.getText(); // sets username equal to whatever was in the username text field
                String password = inputPassword.getText(); // sets password equal to whatever was in the password text field
                Users users = new Users(); //localizes the users class
                try{
                users.analyze(username, password); // sends the local variables "username" and "password" over to the analyze method in the Uers class
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        loginButton.setBounds(232, 151, 104, 24);
        loginWindow.getContentPane().add(loginButton);

        inputUsername = new JTextField();
        inputUsername.setBounds(180, 61, 116, 22);
        loginWindow.getContentPane().add(inputUsername);
        inputUsername.setColumns(10);

        inputPassword = new JTextField();
        inputPassword.setBounds(180, 96, 116, 22);
        loginWindow.getContentPane().add(inputPassword);
        inputPassword.setColumns(10);
        loginWindow.getContentPane().setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{inputUsername, inputPassword, cAccButton, loginButton}));
        loginWindow.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{inputUsername, inputPassword, loginButton, cAccButton}));
    }
}

And the last class

    public class Users {

    private String username = "q"; //created random username for debugging
    private String password = "1"; //created random password for debugging


    public void analyze(String username, String password){ //accepts username and password
        Windows window = new Windows();
        //System.out.println("username :" + username + " password: " + password); //debugging
        if (this.username.equals(username)){ //tests to see if the classes username equals the inputed username
            if (this.password.equals(password)){ //tests to see if the classespassword equals the inputed password  
                window.dMMWindow();
                window.disposeWindow("loginWindow");
                    //what to do once logged in
                    //function once botch username  and password match
            } else { 
                window.displayErrorWindow(); // output for incorrect information
            }
        } else if (!this.username.equals(username)){ //not sure if I need this but i'll keep it
            window.displayErrorWindow();
        }
    }


}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) *"Now I know that this is a bad approach, but I'm making a program and i need users to log in. I thought that if I created two different JFrames (one to log in, and one for my program) that I could just change their respective visibility states to decide which frame I wanted to show."* Use either a `CardLayout` for both main content and log-in in a single frame, or on frame and a `JOptionPane` or modal `JDialog` for the log-in. – Andrew Thompson Dec 03 '15 at 03:34
  • 1
    `loginWindow.getContentPane().setLayout(null);` Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Dec 03 '15 at 03:36
  • 1
    `inputPassword = new JTextField();` If it is for a password, use a [`JPasswordField`](http://docs.oracle.com/javase/8/docs/api/javax/swing/JPasswordField.html)! The password field is specially designed for user security. – Andrew Thompson Dec 03 '15 at 03:39
  • 1
    If you've done even a little searching on solving a NullPointerException (NPE), you'll know that the most important bit of information that we need is the exception's associated stacktrace and some identification of the line that causes it, something that the stacktrace will tell you, and unfortunately neither of which you've posted here with your question. – Hovercraft Full Of Eels Dec 03 '15 at 03:39
  • But having said that, please understand that the heuristic for NullPointerExceptions is almost always the same. **You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully**, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. In the future, please search on the subject before posting, since this is too common a problem to post yet another NPE question. – Hovercraft Full Of Eels Dec 03 '15 at 03:40
  • Myself, I'd make the login window a JDialog and not a JFrame since it is not the main application window. Either that or even better, simply swap views in a JFrame using CardLayout. But neither of these issues have bearing on your NPE problem. – Hovercraft Full Of Eels Dec 03 '15 at 03:41
  • You're creating a new Windows object within Users and are assuming that it is the same as the displayed one, and so when you call `loginWindow.setVisible(false);` and this is generated by Users, you throw a NPE because the loginWindow variable associated with the User's Windows object is null. Solution: don't do this. – Hovercraft Full Of Eels Dec 03 '15 at 03:49
  • Have a look at MadProgrammer's example [here](http://stackoverflow.com/a/17479575/522444) and [here](http://stackoverflow.com/a/24296872/522444) for use of CardLayout and login. – Hovercraft Full Of Eels Dec 03 '15 at 03:52

0 Answers0