java swing JTextField set PlaceHolder [duplicate]
Asked Answered
C

4

32

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("");
Cornew answered 25/4, 2013 at 11:43 Comment(3)
to avoiding (my probably) missinterpetations placeholder is "please input text" or Icon in the case that JTextField is empty ???Lingonberry
What do you mean exactly by placeholder? Maybe this answer can help you?Meso
I wrote my own component. See here: github.com/CollinAlpert/APIs/blob/master/javax/swing/…Gala
D
43

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;
    }

}
Danzig answered 26/4, 2013 at 5:1 Comment(2)
Thank's for a quick replay dearCornew
I found the rendering of the placeholder text looked less than ideal. Based on this SO answer about text rendering, 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 answerDekeles
S
27
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");
        }
    }
    });
Sirajuddaula answered 9/11, 2016 at 21:23 Comment(4)
Welcome to Stack Overflow! This answer can become much more useful by providing some context surrounding your code.Sulfonate
Of course, if you type in the text "Search" and then click back on the field that text will disappear.Ikeikebana
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 ?Sheets
We just need to add searchText.setText("..."); under searchText = new JTextField("Search"); searchText.setForeground(Color.GRAY);Etoile
P
11

So simple use a swingx jar then like this

JTextArea txtMSISDNList = new JTextArea();  
PromptSupport.setPrompt("01197585960,01197585961", txtMSISDNList);
Planoconcave answered 1/12, 2015 at 6:11 Comment(5)
You are most welcome friend.Planoconcave
Your link is broken. Do you have an update for it?Quash
Download the jar file here: java2s.com/Code/Jar/s/Downloadswingx161jar.htmUnexpressed
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 (see "Download" column on the right).Tremolant
If I am using above solution, the background of my Textfield goes grey in Mac.Catenary
M
10

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

Mande answered 25/4, 2013 at 16:12 Comment(1)
Thank's for a quick replay dear camickrCornew

© 2022 - 2024 — McMap. All rights reserved.