Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a default message in JTextField java [duplicate]

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?

like image 918
Gustavo Baiocchi Costa Avatar asked Feb 16 '13 23:02

Gustavo Baiocchi Costa


2 Answers

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.

like image 195
Cyrille Ka Avatar answered Oct 21 '22 01:10

Cyrille Ka


I believe what you want is input hint in the text field, something like the image below:

input hint

Check xswingx library which can do this.

like image 25
iTech Avatar answered Oct 21 '22 03:10

iTech