2013-07-26 36 views
0

在我的代碼中,我嘗試設置Preferences。我有兩個輸入字段:JTextFieldJPasswordFieldJPasswordField可以正常工作,但JTextField不會在內存中保存首選項信息,而是會複製密碼信息。Java首選項JTextField和JPasswordField的問題?

import java.util.prefs.Preferences; 
import javax.swing.*; 


public class TestJP { 

    public static Preferences userPreferences = Preferences.userRoot(); 
    public final static String LOGIN_KEY = ""; 
    public final static String PASSWORD_KEY = ""; 


    public static void main(String[] args) { 


       JTextField login = new JTextField(20); 
       login.setText(userPreferences.get(LOGIN_KEY, "")); 
       JPasswordField password = new JPasswordField(20); 
       password.setText(userPreferences.get(PASSWORD_KEY, "")); 

       JPanel myPanel = new JPanel(); 
       myPanel.add(new JLabel("login:")); 
       myPanel.add(login); 
       myPanel.add(Box.createHorizontalStrut(15)); 
       myPanel.add(new JLabel("password:")); 
       myPanel.add(password); 

       int result = JOptionPane.showConfirmDialog(null, myPanel, 
         "Please Login", JOptionPane.OK_CANCEL_OPTION); 
       if (result == JOptionPane.OK_OPTION) { 

       userPreferences.put(LOGIN_KEY,login.getText()); 
       userPreferences.put(PASSWORD_KEY, password.getText()); 

       } 

      } 

    } 

是否JPasswordField覆蓋莫名其妙的JTextField

+0

沒有引起,請什麼真正的問題,嘗試切換(LOGIN_KEY) 「」 與( 「」,LOGIN_KEY),較好(LOGIN_KEY ,LOGIN_KEY) – mKorbel

回答

2

你的鑰匙都是空的字符串。他們需要是獨特的字符串。

前:

public final static String LOGIN_KEY = ""; 
public final static String PASSWORD_KEY = ""; 

新:

public final static String LOGIN_KEY = "login_key"; 
public final static String PASSWORD_KEY = "password_key"; 
+0

謝謝!它工作正常!但是我仍然感到困惑,即使它是一個空字符串,'JPasswordField'怎麼起作用?謝謝 – Buras

+0

不客氣!查看您保存偏好的順序。密碼最後保存,因此覆蓋您以前保存的登錄前綴。您用作鑰匙的空字符串在技術上仍然是一個有效的密鑰。一個用於登錄和密碼存儲前綴的密鑰。 – JBuenoJr