2015-10-05 38 views
2

所以我開始創建這個項目,爲我的PAT等級12任務,我碰到了一個speedbump ...我有一個登錄屏幕,在NetBeans中使用jFrame。 我的問題是,我正在使用2個文本文件來存儲數據:1個用戶名和1個密碼。他們使用掃描儀閱讀,並用#分隔。 重點是,我使用while循環驗證了用戶名,但我無法驗證與其他文本文件中與該用戶名相對應的密碼。Java jFrame登錄屏幕,從2個文本文件中讀取,netbeans

所以你可以想象2個文本文件:

  • 用戶名
  • 密碼

當點擊「登錄」按鈕,它使用while循環來檢查,看看用戶名已存在。如果是,請繼續輸入密碼,否則「用戶名不存在」。在其他文本文件中將密碼與相同位置上的密碼進行匹配時會出現問題。

如果有人能幫助我,它會使我的一週,並保存我的項目。 請理解,Netbeans只允許您編輯某些代碼區域。我盡我所能保持我的代碼清晰易懂。

非常感謝, SnowyTheVampire

package Battlefield4; 
import javax.swing.*; 
import java.util.*; 
import java.io.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class Login extends javax.swing.JFrame 
{ 

String Username; 
String Password; 

public Login() 
{ 
    initComponents(); 
} 
      //Can not edit from here on  
private void initComponents() { 

    txtUsername = new javax.swing.JTextField(); 
    txtPassword = new javax.swing.JTextField(); 
    lblPassword = new javax.swing.JLabel(); 
    lblUsername = new javax.swing.JLabel(); 
    btnLogin = new javax.swing.JButton(); 
    btnCreate = new javax.swing.JButton(); 
    jLabel1 = new javax.swing.JLabel(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
    setSize(new java.awt.Dimension(854, 480)); 
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); 
    getContentPane().add(txtUsername, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 150, 210, -1)); 
    getContentPane().add(txtPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 220, 210, -1)); 

    lblPassword.setText("Password"); 
    getContentPane().add(lblPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 200, -1, -1)); 

    lblUsername.setText("Username"); 
    getContentPane().add(lblUsername, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 130, -1, -1)); 

    btnLogin.setText("Login"); 
    btnLogin.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      btnLoginActionPerformed(evt); 
     } 
    }); 
    getContentPane().add(btnLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 290, -1, -1)); 

    btnCreate.setText("Create"); 
    btnCreate.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      btnCreateActionPerformed(evt); 
     } 
    }); 
    getContentPane().add(btnCreate, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 290, -1, -1)); 

    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Battlefield4/Batfield/Background/Login (Small).jpg"))); // NOI18N 
    jLabel1.setText("jLabel1"); 
    getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 860, 480)); 

    pack(); 
}       
//Can not edit before this 
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {           
    //This is from where Netbeans lets you edit your code. 
    try { 
     File user = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Username.txt"); //To create a universal file for Input & Output 
     File pass = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Password.txt"); //To create a universal file for Input & Output 
     user.getParentFile().mkdirs(); //To denote the parent file 
     pass.getParentFile().mkdirs(); //To denote the parent file 
     Scanner scUser = new Scanner(user).useDelimiter("#"); //To scan the Username file 
     Scanner scPass = new Scanner(pass).useDelimiter("#"); 
     Username = txtUsername.getText(); //This gets the user input 
     Password = txtPassword.getText(); //This gets the user input 
     int pos = 0; //Indicates the position of the Username in the save file 

     while(scUser.hasNext()) 
     { 
      pos = pos + 1; 

      if(scUser.equals(Username)) 
      { //This is where it fails 
       for (int i = 0; i <= 5; i++) 
       { 
        while(scPass.hasNext()) 
        { 
         System.out.print(scPass); 
        } 
       } 

       if(scPass.equals(Password)) 
       { 
        new Selection().setVisible(true); 
        this.dispose(); 
       } 
       else 
       { 
        JOptionPane.showMessageDialog(null,"Incorrect Password!"); 
       } 
      }//This is where it works from. The above code is sketchy 
      else 
      { 
       JOptionPane.showMessageDialog(null,"User Does Not Exist!"); 
      } 
      scUser.close(); 
     } 
    } 
    catch (FileNotFoundException ex) 
    { 
     Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    catch (IOException ex) 
    { 
     Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); 
    } 

}           

private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {           
    //Again this is from where Netbeans lets you edit 
    try { 
     File user = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Username.txt"); //To create a universal file for Input & Output 
     File pass = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Password.txt"); //To create a universal file for Input & Output 
     user.getParentFile().mkdirs(); //To denote the parent file 
     pass.getParentFile().mkdirs(); //To denote the parent file 
     Scanner scUser = new Scanner(user); //To scan the Username file 
     Username = txtUsername.getText(); //This gets the user input 
     Password = txtPassword.getText(); //This gets the user input 

     if(scUser.nextLine().contains(Username)) //This reads the entire line and checks for an indexOf of those characters 
     { 
      JOptionPane.showMessageDialog(null,"User Already Exists!"); 
      scUser.close(); //Close the Scanner 
     } 
     else 
     { 
      scUser.close(); //Close the Scanner 
      if("".equals(Password) || " ".equals(Password)) //Checks to see whether or not the user entered a password 
      { 
       JOptionPane.showMessageDialog(null,"Please Enter A Password!"); 
      } 
      else 
      { 
       PrintWriter pwUser = new PrintWriter(new FileWriter(user,true)); //To Write to the Username file 
       PrintWriter pwPass = new PrintWriter(new FileWriter(pass,true)); //To Write to the Password file 
       pwUser.print(Username + "#"); 
       pwPass.print(Password + "#"); 
       pwUser.close(); 
       pwPass.close(); 

       new Selection().setVisible(true); 
       this.dispose(); 
      } 
     } 
     scUser.close(); 
    } 
    catch (FileNotFoundException ex) 
    { 
     Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    catch (IOException ex) 
    { 
     Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); 
    } 

}           
//Can no longer edit here 
public static void main(String args[]) { 

    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 

    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new Login().setVisible(true); 
     } 
    }); 
} 

// Variables declaration - do not modify      
private javax.swing.JButton btnCreate; 
private javax.swing.JButton btnLogin; 
private javax.swing.JLabel jLabel1; 
private javax.swing.JLabel lblPassword; 
private javax.swing.JLabel lblUsername; 
private javax.swing.JTextField txtPassword; 
private javax.swing.JTextField txtUsername; 
// End of variables declaration     
} 
+0

只需使用一個文本文件,將用戶名和密碼寫入一行並用特殊字符分隔它們即可。 – Tobi

+0

你到目前爲止嘗試過什麼?請複製粘貼一些代碼,顯示您認爲失敗的位置 –

+1

@Benoît不僅僅是'代碼',而是[MCVE](http://stackoverflow.com/help/mcve)可能是最好的選擇。順便說一句,爲什麼你使用2個文本文件,而不是用同一個'#'來保存它們,以便分隔用戶名和密碼,然後檢索信息並使用split(「#」)來獲取用戶名和密碼變量的數據? – Frakcool

回答

0

所以我想出瞭如何做到這一點。感謝大家的幫助!

我發佈此作爲一種更簡單的方法@Tobi希望幫助那些不是先進的或需要更簡單的幫助的人!

private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {           

    try { 
     File user = new File("src\\Battlefield4\\Batfield\\Users\\Username.txt"); //To create a universal file for Input & Output 
     File pass = new File("src\\Battlefield4\\Batfield\\Users\\Password.txt"); //To create a universal file for Input & Output 
     user.getParentFile().mkdirs(); //To denote the parent file 
     pass.getParentFile().mkdirs(); //To denote the parent file 
     Scanner scUser = new Scanner(user).useDelimiter("#"); //To scan the Username file 
     Scanner scPass = new Scanner(pass).useDelimiter("#"); //To scan the password file 
     username = txtUsername.getText(); //This gets the user input 
     password = txtPassword.getText(); //This gets the user input 
     int pos = 0; //Indicates the position of the Username in the save file 
     boolean loggedIn = false; //Flag to check if it's logged in 

     while(scUser.hasNext() && scPass.hasNext()) //Runs files in congruency 
     { 
      if(scUser.next().equalsIgnoreCase(username) && scPass.next().equals(password)) 
      { 
       loggedIn = true; 
       scUser.close(); 
       scPass.close(); 
       new Selection(username).setVisible(true); 
       this.dispose(); 
       break; 
      } 
     } 
     scUser.close(); 
     scPass.close(); 
     if(loggedIn == false) 
     { 
      JOptionPane.showMessageDialog(null,"Incorrect Username or Password!"); 
     } 

    } 
    catch (FileNotFoundException ex) 
    { 
     Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); 
    } 

}           
1

地圖上啓動的所有用戶,然後就查地圖。使用split來分隔用戶名和密碼。檢查輸入是否爲空之前調用登錄Correct()

private static final Logger LOG = LogManager.getLogger(); 
private final Map<String, String> users = new ConcurrentHashMap<>(); 

public Login() { 
    super(); 
    final InputStream resource = this.getClass().getResourceAsStream("/users.txt"); 
    final Scanner scanner = new Scanner(resource); 
    while (scanner.hasNext()) { 
     final String input = scanner.nextLine(); 
     final String[] userPw = StringUtils.split(input, ':'); 
     this.users.put(userPw[0], userPw[1]); 
    } 
    scanner.close(); 
    IOUtils.closeQuietly(resource); 
} 

public boolean isLoginCorrect(final String username,final String password) { 
    final boolean result; 
    if (StringUtils.equals(this.users.get(username), password)) { 
     result = true; 
    } else { 
     Login.LOG.warn("No such user"); 
     result = false; 
    } 
    return result; 
} 
+0

非常感謝!儘管我不會假裝我已經足夠先進,足以理解所有這些。謝謝! – SnowyTheVampire