javaactionlistenerfocuslistener

Java call "addActionListener" from "FocusListener"


I have JTextField. I need to save the changes, if user writes something in it and then lost the focus(like click some where else)

mMaxLabelLength = new JTextField();
mMaxLabelLength.addActionListener(this);

public void focusGained(FocusEvent fe)
{
    System.out.println("4");
    mMaxLabelLength.addActionListener(this);
}

@Override
public void focusLost(FocusEvent fe)
{
    System.out.println("5");
    mMaxLabelLength.addActionListener(this);
}

    public void actionPerformed(ActionEvent e)
{
    //Do something
    }

The problem is I am not able to call "actionPerformed" from "focusLost/focusGain". I need to keep the "actionPerformed" as separate method as I am calling it from another places also.


Solution

  • So, you want to do exactly the same thing when the focus is lost as what you're already doing in actionPerformed(), right, right. So, do just that:

    @Override
    public void focusLost(FocusEvent fe) {
        doSomething();
    }
    
    public void actionPerformed(ActionEvent e){
        doSomething();
    }
    
    private void doSomething() {
        // ...
    }