2012-02-02 77 views
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

您可以简单地将一个静态块添加到您的程序中,您将在其中进行身份验证,该静态块始终在主方法之前执行。如果用户无效请与

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

这使的感觉很多。我没有真正触及过静态块,直到现在从未真正看到过需要。谢谢,这使得它更清晰。 – user976123 2012-02-02 05:52:33

+0

@ user976123:您的欢迎,很高兴我能帮上忙。问候 – 2012-02-02 05:55:22

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

//如果登录被验证,那么用户程序将进行进一步

+0

+1,为好的解决方法:-)问候 – 2012-02-02 06:47:49

+0

@GagandeepBali谢谢。 – 2012-02-02 06:50:37

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

+1,不错的方法:-) – 2012-02-02 07:10:32

+2

请看[格式化帮助](http://stackoverflow.com/editing-help#code)关于如何格式化代码块:)或者下一次使用{}按钮。 – oers 2012-02-02 09:56:45

相关问题