简体   繁体   中英

How to empty JTextField if gained focus

I am new to java GUI and I have 2 JTextField 's txtMessage1 and txtMessage2 . I'd like to archive this: if one textfiled has focus the other one will be emptied, is that possible and how to archive it?

I tried:

if (txtMessage1.isFocusOwner())
    txtMessage2.setText("");
if (txtMessage2.isFocusOwner())
    txtMessage1.setText("");

But it doesn't work, not throwing anything....

You need a FocusListener for it, like this:

FocusAdapter fl = new FocusAdapter()
{
    public void focusGained (FocusEvent evt)
    {
        if (evt.getSource() == txtField1)
            txtField2.setText("");
        else if (evt.getSource() == txtField2)
            txtField1.setText("");
    }
}
txtField1.addFocusListener(fl);
txtField2.addFocusListener(fl);

You have to define a FocusListener for each JTextField or one single for both.

See the example at the bottom of this page:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM