How to add a placeholder in a JPasswordField

2

As the title of my question indicates, I am trying to add a placeholder in a JPasswordField, however it could be said that I have achieved it halfway.

What I have done so far is to use the following code (which I adapted from an answer I found in SO):

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;

public class TextFieldWithPromptUI extends BasicTextFieldUI implements FocusListener
{
  private final String hint;
  private final boolean hideOnFocus;
  private final Color color;
  private final Font font;

  public TextFieldWithPromptUI(String hint, boolean hideOnFocus, Font font, Color color)
  {
    this.hint = hint;
    this.hideOnFocus = hideOnFocus;
    this.font = font;
    this.color = color;
  }

  @Override
  protected void paintSafely(Graphics g)
  {
    super.paintSafely(g);
    JTextComponent comp = getComponent();    
    if (comp.getText().length() == 0 && (!hideOnFocus || !comp.isFocusOwner()))
    {
      g.setColor(color);
      g.setFont(font);
      int padding = (comp.getHeight() - comp.getFont().getSize()) / 2;
      g.drawString(hint, 2, comp.getHeight() - padding - 1);
    }
  }

  @Override
  public void focusGained(FocusEvent e)
  {
    if (hideOnFocus)
    {
      getComponent().repaint();
    }
  }

  @Override
  public void focusLost(FocusEvent e)
  {
    if (hideOnFocus)
    {
      getComponent().repaint();
    }
  }  
}

This code allows a placeholder to be successfully added to the JPasswordField, but the problem is that the characters that are written in the text box are displayed, that is, the asterics (' * ') that hide these characters no longer appear. .

I enclose an image to appreciate what happens:

I would like to know how I can modify the previous class to adapt it to a JPasswordField. Thank you in advance for your answers and / or comments.

    
asked by Xam 16.07.2018 в 21:03
source

1 answer

1

You can try the following code

            PlaceholderTextField ph = new PlaceholderTextField("hola soy placeholder");
            ph.setColumns(100);
            Font f = ph.getFont();
            ph.setFont(new Font(f.getName(), f.getStyle(), 30));
    
answered by 16.07.2018 в 21:34