Java - 记住/保存输入字段的程序

时间:2012-04-08 09:28:18

标签: java swing save jtextfield

我有一个程序,它使用三个JTextField字段作为主要数据输入字段。我想拥有它,以便当用户终止程序然后再次打开它时,它们的最后一个条目仍然在字段中。

我怎么能实现这个目标?我需要某种数据库还是有更简单的方法?

5 个答案:

答案 0 :(得分:7)

  

我需要某种数据库..

没有。 D / B对于'3弦'来说是过度杀伤。

  

..还是有更简单的方法?

不止一个。

  1. Object serialization
  2. 一个包含3行文字的File
  3. XMLEncoder / Decoder
  4. Properties档案。
  5. Preferences API。
  6. 一个应用程序。使用JWS部署可以使用PersistenceService
  7. 这就是我能想到的全部内容。

答案 1 :(得分:2)

我还建议查看Java Preferences系统,因为这可以处理每个用户或整个系统的保存信息。

举个例子:

void writeMethod() {
    Preferences prefs = Preferences.userNodeForPackage(this);
    prefs.put("key", "value");
}

void readMethodInSameClass() {
    Preferences prefs = Preferences.userNodeForPackage(this);
    prefs.get("key");
}

This description可能比API参考更好。

答案 2 :(得分:2)

实现此目的的最简单方法是在文本字段中添加一个侦听器并使用java首选项api:

textField = new JTextField();
    // set document listener
    textField.getDocument().addDocumentListener(new MyListener());
    // get the preferences associated with your application
    Preferences prefs = Preferences.userRoot().node("unique_string_representing_your_preferences");
    // load previous value
    textField.setText(prefs.get("your_preference_unique_key", ""));

class MyListener implements DocumentListener {

    @Override
    public void changedUpdate(DocumentEvent event) {
        final Document document = event.getDocument();
        // get the preferences associated with your application
        Preferences prefs = Preferences.userRoot().node("unique_string_representing_your_preferences");
        try {
            // save textfield value in the preferences object
            prefs.put("your_preference_unique_key", document.getText(0, document.getLength()));
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertUpdate(DocumentEvent arg0) {
    }

    @Override
    public void removeUpdate(DocumentEvent arg0) {
    }
}

但这样每次更改文本字段中的值时都会保存。如果只想在关闭应用程序时保存它,可以将WindowListener添加到应用程序并写入

  

的windowClosing

方法以前的changedUpdate的内容。

答案 3 :(得分:1)

有一些选项,您可能希望将数据保存到配置文件并在程序开头加载。

答案 4 :(得分:1)

您可以序列化它们并将它们存储在一个文件中:http://www.tutorialspoint.com/java/java_serialization.htm