问题
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?
回答1:
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.
回答2:
Would I need some sort of database..
No. A D/B is overkill for '3 strings'.
..or is there a simpler way?
There's more than one.
- Object serialization.
- A File with 3 lines of text.
- XMLEncoder/Decoder.
- A Properties file.
- The Preferences API.
- An app. deployed using JWS can use the PersistenceService.
That's all I can recall off the top of my head.
回答3:
I would also suggest looking at the Java Preferences system, since this can handle saving information per user or for the whole system.
As an example:
void writeMethod() {
Preferences prefs = Preferences.userNodeForPackage(this);
prefs.put("key", "value");
}
void readMethodInSameClass() {
Preferences prefs = Preferences.userNodeForPackage(this);
prefs.get("key");
}
This description may be better than the API reference.
回答4:
There are some options, you might want to save the data to a configuration file and load it at the beginning of the program.
回答5:
You could serialize them and store them in a file: http://www.tutorialspoint.com/java/java_serialization.htm
来源:https://stackoverflow.com/questions/10061796/java-program-which-remembers-saves-entered-fields