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

4
我需要做的是提示用户输入用户名和密码 (认证在本地完成),如果验证成功,用户就能够访问程序主体。
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);

有没有快捷的方法来解决这个问题?
3个回答

4
你可以使用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);
}

// 如果登录验证通过,则用户程序将进一步进行

3

您可以在程序中添加一个静态块,用于进行身份验证。此静态块始终在主方法之前执行。如果用户无效,则执行以下操作:

System.exit(0);

如果要退出程序,请使用exit()函数。否则,程序将像平常一样开始执行。

以下是一个示例程序,供您参考:

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

这讲得很有道理。我从来没有真正涉及过静态块,也从来没有看到需要,直到现在。谢谢,这使它更清晰了。 - user976123
@user976123:不客气,很高兴能够帮助到您。敬礼。 - nIcE cOw

2
      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
请查看格式帮助以了解如何格式化代码块 :) 或者下次直接使用{}按钮。 - oers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接