• category: swing folder: InputHintPasswordField title: JPasswordFieldにヒント文字列を描画する tags: [JPasswordField, TextLayout, Focus] author: aterai pubdate: 2012-06-04T14:33:56+09:00 description: JPasswordFieldに入力がない場合、ヒント文字列を描画します。 image: https://lh3.googleusercontent.com/-UKh7dosDsR4/T8xFLnpMGwI/AAAAAAAABNY/nxgzH2XN1vo/s800/InputHintPasswordField.png

概要

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(...)をオーバーライドしてヒント文字列を描画しています。

参考リンク

コメント