JTextField
主なデータ入力フィールドとして3 つのフィールドを使用するプログラムがあります。ユーザーがプログラムを終了してから再度開いたときに、最後のエントリがフィールドに残るようにしたいのです。
どうすればこれを達成できますか?ある種のデータベースが必要ですか、それとももっと簡単な方法がありますか?
JTextField
主なデータ入力フィールドとして3 つのフィールドを使用するプログラムがあります。ユーザーがプログラムを終了してから再度開いたときに、最後のエントリがフィールドに残るようにしたいのです。
どうすればこれを達成できますか?ある種のデータベースが必要ですか、それとももっと簡単な方法がありますか?
ある種のデータベースが必要でしょうか。
いいえ。AD/Bは「3ストリング」ではやり過ぎです。
..またはもっと簡単な方法はありますか?
複数あります。
File
3行のテキストを含むA。Properties
ファイル。Preferences
API 。頭のてっぺんから思い出せるのはそれだけです。
これを実現する最も簡単な方法は、リスナーをテキスト フィールドに追加し、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 を追加して、その中に書き込むことができます。
ウィンドウを閉じる
method 以前の changedUpdate の内容。
Java Preferencesシステムも検討することをお勧めします。これは、ユーザーごとまたはシステム全体の情報の保存を処理できるためです。
例として:
void writeMethod() {
Preferences prefs = Preferences.userNodeForPackage(this);
prefs.put("key", "value");
}
void readMethodInSameClass() {
Preferences prefs = Preferences.userNodeForPackage(this);
prefs.get("key");
}
この説明は、API リファレンスよりも優れている可能性があります。
いくつかのオプションがあります。データを構成ファイルに保存し、プログラムの最初にロードすることができます。
それらをシリアライズしてファイルに保存できます: http://www.tutorialspoint.com/java/java_serialization.htm