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

旧巷老猫 提交于 2019-11-29 14:44:44

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();
            }
        });
    }
}

You can use showInputDialog to get the user name

and the below code to get the password

JLabel label = new JLabel("Please enter your password:");
JPasswordField jpf = new JPasswordField();
JOptionPane.showConfirmDialog(null,
  new Object[]{label, jpf}, "Password:",
  JOptionPane.OK_CANCEL_OPTION);

and write a if condition to check the user name and password

if (!isValidLogin()){
//You can give some message here for the user
System.exit(0);
}

// If login is validated, then the user program will proceed further

Xian Gimeno
      String userName = userNameTF.getText();
      String userPassword = userPasswordPF.getText();
        if(userName.equals("xian") && userPassword.equals("1234"))
        {
          JOptionPane.showMessageDialog(null,"Login successful!","Message",JOptionPane.INFORMATION_MESSAGE); 
          // place your main class here... example: new L7();
        }
        else 
        {
           JOptionPane.showMessageDialog(null,"Invalid username and password","Message",JOptionPane.ERROR_MESSAGE); 
           userNameTF.setText("");
           userPasswordPF.setText("");                       
        }  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!