How to force the user to enter a password before entering the main program?

What I need to do is ask the user for a username and password (authentication is performed locally), and if it is verified, the user will be able to access the main body of the program.

public static void main(String[] args){ //String input = JOptionPane.showInputDialog("Enter password to continue: "); //input2 = Integer.parseInt(input); // followed by the creation of the main frame new Cashier3(); Cashier3 frame = new Cashier3(); frame.setTitle("CASHIER 2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); 

Is there any quick way to do this?

+4
source share
3 answers

You can simply add a static block to your program where you will authenticate, this static block is always executed before the main method. If the user is invalid, go to

 System.exit(0); 

to exit the program. In addition, the program starts as usual.

Here is one sample program that will 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(); } }); } } 
+3
source

You can use showInputDialog to get username

and the code below 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 if condition to check username and password

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

// If the login is confirmed, the user program will continue to work

+4
source
  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(""); } 
+2
source

Source: https://habr.com/ru/post/1394336/


All Articles