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.
解决方案
I found this on the oracle forums.
public class TextFieldWithPrompt extends JTextField{
@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
if(getText().isEmpty() && ! (FocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == this)){
Graphics2D g2 = (Graphics2D)g.create();
g2.setBackground(Color.gray);
g2.setFont(getFont().deriveFont(Font.ITALIC));
g2.drawString("zip", 5, 10); //figure out x, y from font's FontMetrics and size of component.
g2.dispose();
}
}