1

I'm trying to get the text of the JTextField erased every time I click on it. I made a addFocusListeneBut no word comes out. I do not understand why

        nick = new JTextField("nick", 5);
    add(nick);
    nick.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            nick.setText("");

        }

        public void focusLost(FocusEvent e) {
            // nothing
        }
    });

    JLabel texto = new JLabel("CLIENTE");
    add(texto);

    ip = new JTextField("Introduce la IP del destinatario", 16);
    add(ip);
    ip.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            ip.setText("");

        }

        public void focusLost(FocusEvent e) {
            // nothing
        }
    });
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
zzxbx
  • 19
  • 3
  • 2
    Possible duplicate of [How to clear JTextField when mouse clicks the JTextField](https://stackoverflow.com/questions/10133366/how-to-clear-jtextfield-when-mouse-clicks-the-jtextfield) – Ishan Thilina Somasiri Jan 20 '18 at 02:51
  • 2
    A FocusListener should work, and in fact you could use the same listener on all your JTextFields by using the FocusEvent's source field. I can't say why it's not working for you and ask that you post a more complete [mcve] program that shows us your problem. – Hovercraft Full Of Eels Jan 20 '18 at 02:56
  • `new FocusAdapter() { public void focusGained(FocusEvent e) { ((JTextComponent) e.getSource()).setText(""); }}` should work for all – Hovercraft Full Of Eels Jan 20 '18 at 02:58
  • The comment about "no text comes out" makes me wonder if your asking something different. Do you need anything else to happen besides clearing the text field? – markspace Jan 20 '18 at 03:41
  • `FocusEvent` is not the needed one, as it would not fire if the editor already has the focus.... – Usagi Miyamoto Jan 20 '18 at 03:56
  • 1
    `I'm trying to get the text of the JTextField erased every time I click on it` - well that would be annoying. First I type something and tab to another field. Then I realize I made a typing mistake and go back to the text field to fix it, only to have all the test be deleted? I suspect you might want something like the [Text Prompt](https://tips4java.wordpress.com/2009/11/29/text-prompt/), which allows you to display a prompt in the text field that is removed when the user enters some text. – camickr Jan 20 '18 at 04:18

0 Answers0