How to add actionlistener to textfield in Java

Rex Endozo picture Rex Endozo · Sep 22, 2014 · Viewed 7.5k times · Source

so this is the concept: Simply, there's a textbox with "Name" as the value, and I wanted that if I click anywhere IN the textbox, the value "Name" will disappear. This is what I've done in my code:

JTextField t1 = new JTextField("Name", 10);

t1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent cl){
                t1.setText(" ");
            }
        });

There's no syntax errors but when I run the program and clicked somewhere in the textbox, nothing happens and the value "Name" is still there

Any help would be greatly appreciated, thank you!

Answer

Mohit picture Mohit · Sep 22, 2014

You can try this:

t1.addFocusListener(new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {
        t1.setText(null); // Empty the text field when it receives focus
    }

});