0

How do I make the text in a JTextField remove itself once the user clicks into the JTextField? The text must reappear when the user clicks out of the JTextField if the JTextField contains no characters. Also, where would I put this code in my JFrame code?

1 Answers1

-1

Working code Demo : You can use MouseAdapter and override MouseListener

As you wan to clear the JtextField when user clicks inside it. You need to add addMouseListener and override mouseClicked.

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class ClearJtextField {

    public ClearJtextField() {

        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout(FlowLayout.CENTER, 120, 120));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField tf = new JTextField("Type something and click");
        // adding MouseAdapter and overriding mouseClicked
        tf.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                tf.setText("");
            }
        });

        frame.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                if (tf.getText().length() == 0)
                    tf.setText("Type something and click");

            }

        });

        frame.add(tf);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new ClearJtextField();

    }

}

Above code will clear the JTextField on click and again set text back to "Type something and click" if JTextField is empty when user click outside the JTextField.

Abhi
  • 995
  • 1
  • 8
  • 12
  • This does not answer the question. You code does not restore the text if the textfield loses focus and it's empty. – SurfMan Feb 22 '18 at 10:23
  • @SurfMan I have updated the code, Kindly check for the same. – Abhi Feb 22 '18 at 10:40
  • This is a mess. A MouseListener on the frame? Go check the answers on [the duplicate question](https://stackoverflow.com/questions/13033600/java-placeholder-on-textfield) to see a proper solution. – SurfMan Feb 22 '18 at 11:12