• 追加された行はこの色です。
  • 削除された行はこの色です。
---
category: swing
folder: WatermarkInTextField
title: JTextFieldに透かし画像を表示する
tags: [JTextField, Focus, ImageIcon]
author: aterai
pubdate: 2009-10-26T13:04:26+09:00
description: JTextFieldの文字列が空でフォーカスがない場合、透かし画像を表示するように設定します。
image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTWh1Qjh4I/AAAAAAAAApY/bLarzjLy7-8/s800/WatermarkInTextField.png
---
* 概要 [#l4413cba]
* 概要 [#summary]
`JTextField`の文字列が空でフォーカスがない場合、透かし画像を表示するように設定します。

#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTWh1Qjh4I/AAAAAAAAApY/bLarzjLy7-8/s800/WatermarkInTextField.png)

* サンプルコード [#bef878a0]
* サンプルコード [#sourcecode]
#code(link){{
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();
  }
}
}}

* 解説 [#kcbc0705]
* 解説 [#explanation]
- 上
-- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]
- 下
-- `JTextField`の文字列が空で、フォーカスも無い場合、上記のように文字列ではなく、画像を表示します。
-- `JTextField`の文字列が空でフォーカスも無い場合、文字列ではなく画像を表示

----
[[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]では、`JPasswordField`に応用できないので、以下のように透かし画像の表示と同じような方法で文字列を表示します。

- [[JPasswordFieldにヒント文字列を描画する>Swing/InputHintPasswordField]] に移動

* 参考リンク [#w2323b40]
* 参考リンク [#reference]
- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]
- [[JPasswordFieldにヒント文字列を描画する>Swing/InputHintPasswordField]]
-- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]では、`JPasswordField`に応用できないので、`JLabel`を配置することでヒント文字列を表示

* コメント [#rbb7650a]
* コメント [#comment]
#comment
#comment