Search code examples
javaswingsavejtextfield

Java - Program which remembers/saves entered fields


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?


Solution

  • 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) {
        }
    }
    

    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.