【问题标题】:Java Preferences JTextField and JPasswordField issue?Java Preferences JTextField 和 JPasswordField 问题?
【发布时间】:2013-07-26 17:42:52
【问题描述】:

在我的代码中,我尝试设置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

【问题讨论】:

  • 不是造成的,请问什么是真正的问题,尝试切换(LOGIN_KEY),“”与(“”,LOGIN_KEY),更好(LOGIN_KEY,LOGIN_KEY)

标签: java swing jtextfield preferences jpasswordfield


【解决方案1】:

您的键都是空字符串。它们必须是唯一的字符串。

之前:

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";

【讨论】:

  • 谢谢!它工作完美!但是我仍然很困惑,即使它是一个空字符串,它为什么对JPasswordField 起作用?谢谢
  • 不客气!查看您保存首选项的顺序。密码是最后保存的,因此会覆盖您之前保存的登录首选项。您用作密钥的空字符串在技术上仍然是有效的密钥。用于登录名和密码存储首选项的密钥。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
相关资源
最近更新 更多