概要

JTextFieldの文字列が空でフォーカスがない場合、透かし画像を表示するように設定します。

サンプルコード

class WatermarkTextField extends JTextField implements FocusListener {
  private final ImageIcon image;
  private boolean showWatermark = true;
  public WatermarkTextField() {
    super();
    image = new ImageIcon(getClass().getResource("watermark.png"));
    addFocusListener(this);
  }

  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (showWatermark) {
      Graphics2D g2 = (Graphics2D) g.create();
      // Insets i = getMargin();
      Insets i = getInsets();
      int yy = (getHeight() - image.getIconHeight()) / 2;
      g2.drawImage(image.getImage(), i.left, yy, this);
      g2.dispose();
    }
  }

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

  @Override public void focusLost(FocusEvent e) {
    showWatermark = "".equals(getText().trim());
    repaint();
  }
}
View in GitHub: Java, Kotlin

解説

参考リンク

コメント