javaswingjtextfieldfocuslistener

JTextField select all content when focus gained


I have a class implements FocusListener, inside the class got a lot of JTextField, I want all of them select all when the focus gained. This is my focusGained() function:

@Override
public void focusGained(FocusEvent fe)
{
    JTextField txt = (JTextField)fe.getComponent();
    txt.selectAll();
}

I try to convert fe to component then selectAll(), but it doesn't works. Any idea about this?


Solution

  • You need to use getSource()

    ((JTextField)fe.getSource()).selectAll();
    

    I'd personnally check the instanceof fe.getSource()

    @Override
    public void focusGained(FocusEvent fe) {
        if (!(fe.getSource() instanceof JTextField)) return;
        JTextField txt = (JTextField)fe.getSource();
        txt.selectAll();
    }