29

I created a JTextField and now I want to set the placeholder on that JTextField, but I don't know how? Please help. Here is my code:

JTextField database=new JTextField("Enter Data Base Name");
database.setPreferredSize(database.getPreferredSize());
database.setText("");
Jasperan
  • 2,154
  • 1
  • 16
  • 40
Renish Khunt
  • 5,620
  • 18
  • 55
  • 92
  • 1
    to avoiding (my probably) missinterpetations placeholder is "please input text" or Icon in the case that JTextField is empty ??? – mKorbel Apr 25 '13 at 11:51
  • What do you mean exactly by placeholder? Maybe this [answer](http://stackoverflow.com/a/10507193/928711) can help you? – Guillaume Polet Apr 25 '13 at 12:05
  • I wrote my own component. See here: https://github.com/CollinAlpert/APIs/blob/master/javax/swing/JTextBox.java – Collin Alpert Apr 08 '18 at 15:42

4 Answers4

39

Try this class:

package playground;

import java.awt.*;

import javax.swing.*;
import javax.swing.text.Document;

@SuppressWarnings("serial")
public class PlaceholderTextField extends JTextField {

    public static void main(final String[] args) {
        final PlaceholderTextField tf = new PlaceholderTextField("");
        tf.setColumns(20);
        tf.setPlaceholder("All your base are belong to us!");
        final Font f = tf.getFont();
        tf.setFont(new Font(f.getName(), f.getStyle(), 30));
        JOptionPane.showMessageDialog(null, tf);
    }

    private String placeholder;

    public PlaceholderTextField() {
    }

    public PlaceholderTextField(
        final Document pDoc,
        final String pText,
        final int pColumns)
    {
        super(pDoc, pText, pColumns);
    }

    public PlaceholderTextField(final int pColumns) {
        super(pColumns);
    }

    public PlaceholderTextField(final String pText) {
        super(pText);
    }

    public PlaceholderTextField(final String pText, final int pColumns) {
        super(pText, pColumns);
    }

    public String getPlaceholder() {
        return placeholder;
    }

    @Override
    protected void paintComponent(final Graphics pG) {
        super.paintComponent(pG);

        if (placeholder == null || placeholder.length() == 0 || getText().length() > 0) {
            return;
        }

        final Graphics2D g = (Graphics2D) pG;
        g.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(getDisabledTextColor());
        g.drawString(placeholder, getInsets().left, pG.getFontMetrics()
            .getMaxAscent() + getInsets().top);
    }

    public void setPlaceholder(final String s) {
        placeholder = s;
    }

}
Sudhir Dhumal
  • 902
  • 11
  • 22
Peter Tseng
  • 13,613
  • 4
  • 67
  • 57
  • Thank's for a quick replay dear – Renish Khunt Apr 26 '13 at 11:05
  • I found the rendering of the placeholder text looked less than ideal. Based on [this SO answer about text rendering](https://stackoverflow.com/a/31537742/1348743), I added the static field: `private static Map, ?> hints = (Map, ?>) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints");` Then changed the line that sets the rendering hints to `if (hints != null) g.setRenderingHints(hints); else // set them directly as shown in the answer` – Javaru Aug 28 '21 at 00:00
24
JTextField searchText;

...

In constructor:

searchText = new JTextField("Search");
searchText.setForeground(Color.GRAY);
searchText.addFocusListener(new FocusListener() {
    @Override
    public void focusGained(FocusEvent e) {
        if (searchText.getText().equals("Search")) {
            searchText.setText("");
            searchText.setForeground(Color.BLACK);
        }
    }
    @Override
    public void focusLost(FocusEvent e) {
        if (searchText.getText().isEmpty()) {
            searchText.setForeground(Color.GRAY);
            searchText.setText("Search");
        }
    }
    });
Graywolf
  • 299
  • 2
  • 6
  • 3
    Welcome to Stack Overflow! This answer can become much more useful by providing some context surrounding your code. – Joe C Nov 09 '16 at 21:25
  • Of course, if you type in the text "Search" and then click back on the field that text will disappear. – Jeff Demanche Jun 26 '18 at 15:40
  • i love this code , but the text is visible only after clicking the box, i have set the text before also to tackle this issue. Is there a better way ? – Arun Joseph Dec 27 '18 at 09:50
  • We just need to add searchText.setText("..."); under searchText = new JTextField("Search"); searchText.setForeground(Color.GRAY); – Didier Apr 20 '20 at 09:01
11

So simple use a swingx jar then like this

JTextArea txtMSISDNList = new JTextArea();  
PromptSupport.setPrompt("01197585960,01197585961", txtMSISDNList);
Nicola Isotta
  • 202
  • 3
  • 10
Mahfuz Ahmed
  • 721
  • 9
  • 23
  • 1
    Such an simplest way. Thanks a lot friend. – Karthikeyan Mar 18 '16 at 09:37
  • You are most welcome friend. – Mahfuz Ahmed Mar 20 '16 at 13:30
  • Your link is broken. Do you have an update for it? – wanderer0810 Jan 29 '18 at 15:23
  • 2
    Download the jar file here: http://www.java2s.com/Code/Jar/s/Downloadswingx161jar.htm – Lin Jul 03 '18 at 04:49
  • 2
    Unfortunately swingx isn't in development anymore, so use at your own risk (not sure if it's even compatible with Java 8). Important: No matter how trustworthy java2s.com seems, do NOT download jar files from anywhere except the original homepage EVER (you never know what's inside otherwise!)! You can still get the jar through [maven](https://maven.java.net/#nexus-search;gav~org.swinglabs.swingx~swingx-all~~~~kw,versionexpand) (see "Download" column on the right). – Neph Sep 18 '19 at 09:19
  • If I am using above solution, the background of my Textfield goes grey in Mac. – Vaibhav Jain Oct 06 '19 at 14:20
10

If I understand the question, Text Prompt shows one way you can do this.

camickr
  • 321,443
  • 19
  • 166
  • 288