2012-02-02 73 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

相關問題