Java - placeholder on textfield

后端 未结 3 1026
情深已故
情深已故 2020-11-29 08:50

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

3条回答
  •  囚心锁ツ
    2020-11-29 09:27

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

    https://forums.oracle.com/forums/thread.jspa?threadID=1349874

提交回复
热议问题