I am having trouble removing focus listener after adding it to JFormattedTextField. I read about removeFocusListener, but couldn't find examples how to use it. It seems easy enough but no matter what I try it wouldn't work.
Here's a relevant part of the code, where I add the listener, do what I need with it, and where I want to remove it:
private JFormattedTextField heightArea;
heightArea.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
heightArea.setText(getHeight(widthArea));
}
@Override
public void focusLost(FocusEvent e) {
}
});
// From here on I want to remove this listener.
I would try things like:
heightArea.removeFocusListener(new FocusListener() );
or
heightArea.removeFocusListener(heightArea.FocusListener() );
But of course it didn't work. I am not really sure what I should pass to the removeFocusListener from heightArea to remove that focus listener.
Sorry for my inexperience, hopefully you can point me towards the right direction, so I could understand what I am doing wrong.
Any help is appreciated, thank you very much.
Create a class MyFocusListener and declare a class level variable of the same type. Something like this
MyFocusListener myFocusListener = new MyFocusListener();
class MyFocusListener implements FocusListener {
@Override
public void focusGained(FocusEvent e) {
// add your logic here
}
@Override
public void focusLost(FocusEvent e) {
}
}
Then add/remove this listener to your textfield
heightArea.addFocusListener(myFocusListener);
heightArea.removeFocusListener(myFocusListener);