Java Preferences JTextField和JPasswordField问题?

时间:2013-07-26 17:42:53

标签: java swing jtextfield preferences jpasswordfield

在我的代码中,我尝试设置Preferences。我有两个输入字段:JTextFieldJPasswordFieldJPasswordField工作正常,但JTextField不会在内存中保留首选项信息,而是复制密码信息。

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

1 个答案:

答案 0 :(得分: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";