I want to create a JTextField with a message inside as a deafult. But not as a proper text but as a comment about what to type inside the JTextField. So if i type jtf.getText() it returns null or empty because it is just a comment that was printed there. When you click on it then it disappears and you can write whatever you want on it. Is there any method to do such a thing?
A possible technique is to first set the default string as the text of the textField:
JTextField myField = new JTextField("Default Text");
Then use a FocusListener
, so that when the user put the focus in the element, the text disappears:
myField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
myField.setText("");
}
public void focusLost(FocusEvent e) {
// nothing
}
});
But you have to be careful: if the user never put the focus in the text field, getText() will return the default string. Therefore, you'd better manage a boolean that tells if the text field has ever had the focus.