概要

JPasswordFieldに入力がない場合、ヒント文字列を描画します。

サンプルコード

class WatermarkPasswordField extends JPasswordField
                             implements FocusListener, DocumentListener {
  private boolean showWatermark = true;
  public WatermarkPasswordField() {
    super();
    addFocusListener(this);
    getDocument().addDocumentListener(this);
  }

  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (showWatermark) {
      Graphics2D g2 = (Graphics2D) g.create();
      Insets i = getInsets();
      Font font = getFont();
      FontRenderContext frc = g2.getFontRenderContext();
      TextLayout tl = new TextLayout("Password", font, frc);
      g2.setPaint(hasFocus() ? Color.GRAY : Color.BLACK);
      int baseline = getBaseline(getWidth(), getHeight());
      tl.draw(g2, i.left + 1, baseline);
      g2.dispose();
    }
  }

  @Override public void focusGained(FocusEvent e) {
    repaint();
  }

  @Override public void focusLost(FocusEvent e) {
    showWatermark = getPassword().length == 0;
    repaint();
  }

  @Override public void insertUpdate(DocumentEvent e) {
    showWatermark = e.getDocument().getLength() == 0;
    repaint();
  }

  @Override public void removeUpdate(DocumentEvent e) {
    showWatermark = e.getDocument().getLength() == 0;
    repaint();
  }

  @Override public void changedUpdate(DocumentEvent e) {}
}
View in GitHub: Java, Kotlin

解説

  • JPasswordField#paintComponent(...)をオーバーライドしてヒント文字列を描画

参考リンク

コメント