java必输字段,Java - 记住/保存输入字段的程序

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值