1

The following code adds Listeners to several SWT Text elements. The only difference is the code inside the Listeners method. Is there a way to make this code less repetitive by finding the correct method to use dynamically?

In this example a FocusListener is used, but it's not relevant.

private void addFocusLostListeners() {
    nameText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setName(nameText.getText());
        }
    });
    ageText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setAge(ageText.getText());
        }
    });
    emailText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setEmail(emailText.getText());
        }
    });
    ...
}
Sadık
  • 4,249
  • 7
  • 53
  • 89
  • first of all use `FocusAdapter` and you won't need to override unused methods ... – Adrian May 15 '19 at 09:54
  • @Adrian it's not clear to me what you are suggesting. – Sadık May 15 '19 at 10:53
  • you don't use `focusGained` from `FocusListener` interface. For such cases in AWT we have adapters, so instead of `new FocusListener()` use `new FocusAdapter()` and override just `focusLost` method – Adrian May 15 '19 at 10:57

1 Answers1

4

You could make a helper method (you need to replace TextField with the actual class of nameText, ageText, etc.):

private static void addFocusListener(TextField field, Consumer<? super String> setter) {
    field.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            setter.accept(field.getText());
        }
    });
}

Which you then could call:

private void addFocusLostListeners() {
    addFocusListener(nameText, myDataObject::setName);
    addFocusListener(ageText, myDataObject::setAge);
    addFocusListener(emailText, myDataObject::setEmail);
}
Lino
  • 19,604
  • 6
  • 47
  • 65
  • but what if myDataObject is null when calling addFocusLostListeners()? – Sadık May 15 '19 at 10:43
  • 2
    @Sadik just replace the method references (e.g. `myDataObject::setName`) with a lambda (e.g. `s -> myDataObject.setName(s)`) this should solve the problem – Lino May 15 '19 at 10:46