user5953547
user5953547

Reputation:

Ghost text in jTextField swing

Have a problem with GUI. How to add text in jTextFiled that will disappear when I click on this field? Have no idea how to realize this. jTextField has only one field for this property. Thank you!

Upvotes: 0

Views: 2572

Answers (2)

Mario Sandoval
Mario Sandoval

Reputation: 1

    import javax.swing.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class GhostTextExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Ghost Text Example");
        JTextArea textArea = new JTextArea(10, 30);

        // Set the default message as ghost text
        textArea.setText("Type your message here...");
        textArea.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if (textArea.getText().equals("Type your message here...")) {
                    textArea.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (textArea.getText().isEmpty()) {
                    textArea.setText("Type your message here...");
                }
            }
        });

Upvotes: 0

camickr
camickr

Reputation: 324207

You can use the Text Prompt class which adds this functionality to any text field.

You have a property to control when the prompt is displayed.

The class basically adds a child (JLabel) to the text field which is painted when the text field doesn't have any text.

Upvotes: 1

Related Questions