2017-02-12 15 views
-1

我有一個錯誤,而在這個Java Swing代碼驗證用戶名和密碼寫道:錯誤的登錄表單使用的Java Swing(與數據庫文件)

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 
import java.util.*; 

public class LoginForm extends JFrame implements ActionListener { 
    private JButton login; 
    private JTextField name; 
    private JPasswordField pw; 

    private LoginForm() { 
     super("Log in"); 
     login = new JButton("Log in"); 
     name = new JTextField(20); 
     pw = new JPasswordField(20); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setLayout(new BorderLayout()); 
     JPanel fields = new JPanel(new BorderLayout()); 
     fields.add(name, "North"); 
     fields.add(new JScrollPane(), "Center"); 
     fields.add(pw, "South"); 
     add(fields, "Center"); 
     add(new JPanel(), "South"); 
     add(new JPanel(), "North"); 
     JPanel j = new JPanel(); 
     j.setSize(100, 400); 
     j.add(login); 
     //j.add(new JLabel("|\n|\n|-> Username")); 
     setSize(600, 400); 
     add(j, "West"); 
     login.addActionListener(this); 
     setVisible(true); 
    } 

    public static void main(String[] args) { 
     new LoginForm(); 
    } 

    public void actionPerformed(ActionEvent evt) { 
     if (evt.getSource() == login) { 
      if (!validUser(name.getText(), pw.getPassword())) JOptionPane.showMessageDialog(null, "This user not exists.\nFor create a user,\n edit 'database.lfrm' file." 
       , "Error!", JOptionPane.ERROR_MESSAGE); 
      else JOptionPane.showMessageDialog(null, "This user is valid! Congraulations!"); 
     } else throw new RuntimeException("Event source isn't be a " + login.toString()); 
    } 
    private static boolean validUser(String name, char[] pwd) { 
     boolean res = false; 
     try { 
      BufferedReader br = new BufferedReader(new FileReader("database.lfrm")); 
      String all = "", lines[], user[], line; 
      while ((line = br.readLine()) != null) all += line; 
      lines = all.split("\n"); 
      user = Arrays.asList(lines).get(Arrays.asList(lines).indexOf(name + " $ " + new String(pwd))).split(" $ "); 
      if (user == new String[]{name, new String(pwd)}) res = true; 
     } catch (IOException e) {e.printStackTrace();} 
     return res; 
    } 
} 

我編譯和運行此代碼,我有這個 「錯誤」:

此用戶不存在
爲了創建一個用戶,編輯 'database.lfrm' 文件

我 'database.lfrm' 文件是喜歡這樣的:

JavaUser $ adimn

回答

2

我想這個問題是在這裏:

if (user == new String[]{name, new String(pwd)}) res = true; 

當你做到這一點,你如果選中‘用戶’和字符串[]元素是相同的對象,不正確,因爲String []元素是您爲此驗證創建的另一個對象。

要檢查什麼是如果「用戶」陣列和下一個數組的內容是相同的,這可以解決通過更換這行:

if (Arrays.equals(user, new String[] {name, new String(pwd)})) res = true; 
+0

感謝您的回答。它是正確的。 – Muskovets