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.
I believe what you want is input hint
in the text field, something like the image below:
Check xswingx library which can do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With