如何在进入主程序之前提示用户输入密码?

我需要做的是用用户名和密码提示用户(身份validation在本地完成),如果签出,用户就可以访问主程序体。

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

有什么快速的方法可以做到这一点?

您只需将静态块添加到您将进行身份validation的程序中,此静态块始终在main方法之前执行。 如果用户无效,请选择

 System.exit(0); 

退出程序。 否则程序将照常开始执行。

这是一个示例程序,可以给你一些想法:

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

您可以使用showInputDialog来获取用户名

和以下代码获取密码

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

并写一个if条件来检查用户名和密码

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

//如果validation登录,则用户程序将继续进行

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