Java - placeholder on textfield

Jordashiro picture Jordashiro · Oct 23, 2012 · Viewed 24.4k times · Source

I'm trying to create a GUI with Swing. My problem is, I have a textfield, but I want it to have a "placeholder" (like in html). I read here and there that it can be done by overriding the paint() of the textfield.

Since my code is generated I found out that I need to use the "Custom Creation Code" to override the code that was generated.

Here is what I have put in the "Custom Creation Code" field

new javax.swing.JTextField()
{
    String test = super.getText();
    String hint = "Username";

    public void paint(Graphics g)
    {
        if ( test == null || test.length() < 1 ) {
            g.setColor( Color.red );
            g.drawString(hint, 0, 0);
        }

        g.setColor(Color.BLACK);
        super.paint(g);
    }
}

This generates the following output

javax.swing.JTextField username = new javax.swing.JTextField()
{
    String test = super.getText();
    String hint = "Username";

    public void paint(Graphics g)
    {
        if ( test == null || test.length() < 1 ) {
            g.setColor( Color.red );
            g.drawString(hint, 0, 0);
        }

        g.setColor(Color.BLACK);
        super.paint(g);
    }
};

For now I see the textField but there is nothing in it, maybe I need to add some function onto some event, but I am not sure.

I would be grateful if anyone could lend a hand.

EDIT : Here is a demo of what I want to do : http://davidwalsh.name/demo/html5-placeholder.php

Answer

MadProgrammer picture MadProgrammer · Oct 23, 2012

I use to override the text fields paint method, until I ended up with more custom text fields then I really wanted...

Then I found this prompt API which is simple to use and doesn't require you to extend any components. It also has a nice "buddy" API

This has now been included in the SwingLabs, SwingX library which makes it even eaiser to use...