2

I want to make my text field clear the text when someone clicks it. How can I do this?

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132
Strawberry
  • 66,024
  • 56
  • 149
  • 197

3 Answers3

9

on java.awt.TextField you can add a MouseListener like so

TextField field = new TextField();
field.addMouseListener(new MouseListener() {

    public void mouseClicked(MouseEvent e) {

    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }

});

The reason being that java.awt.TextField is a subclass of java.awt.TextComponent (which, in turn, is a subclass of java.awt.Component). The Component class has a addMouseListener() method.

Alternatively, you can replace MouseListener with java.awt.event.MouseAdapter has it encapsulates all of MouseListener, MouseWheelListener and MouseMotionListener methods.

From JavaDoc (of MouseAdapter):

An abstract adapter class for receiving mouse events. The methods in this class are empty. This class exists as convenience for creating listener objects.

Mouse events let you track when a mouse is pressed, released, clicked, moved, dragged, when it enters a component, when it exits and when a mouse wheel is moved.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • Even though I am using only MousePressed, why does eclipse make me have empty functions for all of the others? – Strawberry Dec 01 '10 at 12:29
  • 1
    @Doug, because you're implementing an interface and not an abstract class. If you want just `mousePressed`, use `MouseAdapter` instead. – Buhake Sindi Dec 01 '10 at 12:37
4

Probably, you need addMouseListener().

upd It would be smt like

TextField a = ...;
  a.addMouseListener(new MouseAdapter(){
   public void mouseReleased(MouseEvent e) {
    //some stuff
   }
});

upd2 fix keyListener to MouseListener

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132
0

Try this:

  TextField.setText("defaultText");

    TextField.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            reSet(evt);
        }
    });

  TextField.addFocusListener(new java.awt.event.FocusAdapter() {
        public void focusGained(java.awt.event.FocusEvent evt) {
            reSet(evt);
        }
  });

  void reSet(java.awt.event.KeyEvent evt) {
      String temp = jTextField1.getText();
      TextField.setText(temp.equals("defaultText")? "" : temp);
  }
Mohamed Saligh
  • 12,029
  • 19
  • 65
  • 84
  • Not sure here: isn't `focusGained(FocusEvent)` fired always when `Component` gets focus, i.e. when you alt+tab to your JFrame? – Przemek Kryger Dec 01 '10 at 11:58