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