I have seen many questions and answers regarding enter key handling in text fields.
It seems that I can either listen to the value change event or that I have to bind a shortcut to a button.
I now have another requirement, we have the following screen:
When a user enters text in textfield1.1 and then presses ENTER in that field, we fire <gobutton1.1>.
We don’t wish to fire the command when the user enters text but does not hit enter in the field, so the value change event would not help us.
And binding the short cut to one (or all) of the go buttons would not help, since we don’t know which one to search for when enter is hit.
Of course we could scan all text fields and look if we have some text in them, but then we would not be sure if the user did hit enter in a specific field.
One possible solution would be using the Action.Handler combined with the FieldEvents.FocusListener() which is added for each textfield. The FocusListener would update the lastFocusedField variable. Thus, when the enter is hit one would know that the focus were in the lastFocusedField textfield.
Another solution may be to use multiple Panels, each having its own Action.handler, for each textfield go-button pairs.
Example code for the first solution proposal is below.
private Window mainWindow;
Action action_enter = new ShortcutAction("Default key",
ShortcutAction.KeyCode.ENTER, null);
private TextField lastFocusedField = null;
public void init() {
mainWindow = new Window();
mainWindow.addActionHandler(this);
VerticalLayout vlo = new VerticalLayout();
HorizontalLayout hlo1 = new HorizontalLayout();
HorizontalLayout hlo2 = new HorizontalLayout();
vlo.addComponent(hlo1);
vlo.addComponent(hlo2);
TextField textField1 = new TextField();
TextField textField2 = new TextField();
textField1.addListener(new FieldEvents.FocusListener() {
public void focus(FocusEvent event) {
lastFocusedField = (TextField) event.getComponent();
}
});
textField2.addListener(new FieldEvents.FocusListener() {
public void focus(FocusEvent event) {
lastFocusedField = (TextField) event.getComponent();
}
});
Button b1 = new Button();
Button b2 = new Button();
hlo1.addComponent(textField1);
hlo1.addComponent(b1);
hlo2.addComponent(textField2);
hlo2.addComponent(b2);
mainWindow.addComponent(vlo);
setMainWindow(mainWindow);
}
public Action[] getActions(Object target, Object sender) {
return new Action[] { action_enter };
}
public void handleAction(Action action, Object sender, Object target) {
if (action == action_enter) {
System.out.println(lastFocusedField.getValue());
}
}