Java - 记住/保存输入字段的程序 [英] Java - Program which remembers/saves entered fields

查看:176
本文介绍了Java - 记住/保存输入字段的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program that uses three JTextField fields as the main data entry fields. I want to have it so that when the user terminates the program and then opens it again, their last entry will still be in the fields.

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

How could I achieve this? Would I need some sort of database or is there a simpler way?

推荐答案

实现这一目标的最简单方法是添加一个监听器到文本字段并使用java首选项api:

the simplest way to achieve this is to add a listener to the text field and use the java preferences 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添加到应用程序并写入

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

windowClosing

方法上一次更改的更新内容。

method the content of the previous changedUpdate.

这篇关于Java - 记住/保存输入字段的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆