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

时间:2012-02-02 05:08:25

标签: java swing user-interface joptionpane

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

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 个答案:

答案 0 :(得分: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);
}

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

答案 1 :(得分:3)

您只需在程序中添加一个静态块,您将在其中进行身份验证,此静态块始终在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();
            }
        });
    }
}

答案 2 :(得分: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("");                       
        }