1

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

我怎么能做到这一点?我需要某种数据库还是有更简单的方法?

4

5 回答 5

7

我需要某种数据库吗..

不,AD/B 对于“3 个字符串”来说太过分了。

..或者有更简单的方法吗?

不止一个。

  1. 对象序列化
  2. File带有 3 行文本的 A。
  3. XML编码器/解码器
  4. 一个Properties文件。
  5. PreferencesAPI 。
  6. 一个应用程序。使用JWS部署可以使用PersistenceService

这就是我能想到的全部。

于 2012-04-08T09:49:10.613 回答
2

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

举个例子:

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

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

这个描述可能比 API 参考更好。

于 2012-04-08T09:40:15.800 回答
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) {
    }
}

but in this way every time you change value in the text field it is saved. If you want to save it only when application is closed, you can add a WindowListener to your application and write in its

windowClosing

method the content of the previous changedUpdate.

于 2012-04-08T10:36:24.127 回答
1

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

于 2012-04-08T09:31:04.597 回答
1

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

于 2012-04-08T09:31:20.757 回答