Reputation: 53129
I have a Settings
class that should provide interface for retrieving settings and saving them to a file. My settings are supposed to update whenever I change input values (rather than after clicking Save button). This is why I added this method to Settings
class:
/** Automatically update setting value as user types.
* @param setting_name What is the name of associated setting?
* @param input JTextComponent (like JTextField) to listen on for events
*/
public void listenOnInput(final String setting_name, final JTextComponent input) {
//Debug output
System.out.println("Settings[\""+setting_name+"\"] automatically updates on input change.");
input.addInputMethodListener(new InputMethodListener() {
@Override
public void inputMethodTextChanged(InputMethodEvent event) {
//Set setting to current value
setSetting(setting_name, input.getText());
}
//This method is dummy, I see no use for it
@Override
public void caretPositionChanged(InputMethodEvent event) {}
});
}
It's probably not perfect design, but my application will never have complex settings therefore I don't put so much effort in this task. I use it like this:
JTextField name = new JTextField();
Settings settings = new Settings();
name.setToolTipText("Enter your name");
contentPane.add(name);
settings.listenOnInput("user_name", name);
My problem is that the code above doesn't work - I can type or press Enter but the inputMethodTextChanged
is never called.
So what's proper method of obtaining the value on update?
Upvotes: 0
Views: 1895
Reputation: 466
Use a DocumentListener
on the JTextField
's document:
textField.getDocument().addDocumentListener(...);
You can then use it to detect any change in the text.
Upvotes: 2