I want to make my text field clear the text when someone clicks it. How can I do this?
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
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);
}
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.