How do I Prompt the user to enter a password before entering the main program?

前端 未结 3 1380
庸人自扰
庸人自扰 2020-12-21 02:16

What I need to do is to prompt the user with a username and password (authentication is done locally) and if it checks out, the user would then be able to access the main pr

3条回答
  •  情书的邮戳
    2020-12-21 02:52

    You can simply add a static block to your program where you will do your authentication, this static block is always executed before the main method. If the user is not valid go with

    System.exit(0);
    

    to exit the program. Else the program will start execution as usual.

    Here is one sample program to give you some idea :

    import java.awt.Color;
    import javax.swing.*;
    
    public class Validation extends JFrame
    {
        private static Validation valid = new Validation();
        static
        {
            String choice = JOptionPane.showInputDialog(valid, "Enter Password", "Password", JOptionPane.PLAIN_MESSAGE);
            if ((choice == null) || ((choice != null) && !(choice.equals("password"))))
                System.exit(0);
        }
    
        private static void createAndDisplayGUI()
        {
            valid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            valid.setLocationRelativeTo(null);
    
            valid.getContentPane().setBackground(Color.YELLOW);
    
            valid.setSize(200, 200);
            valid.setVisible(true);
        }
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndDisplayGUI();
                }
            });
        }
    }
    

提交回复
热议问题