Swing/WatermarkInTextField のバックアップ(No.10)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/WatermarkInTextField へ行く。
  - 1 (2009-10-26 (月) 13:04:26)
- 2 (2009-10-26 (月) 16:40:09)
- 3 (2011-05-18 (水) 16:01:36)
- 4 (2012-06-01 (金) 16:26:00)
- 5 (2012-06-04 (月) 14:31:35)
- 6 (2013-01-05 (土) 19:44:05)
- 7 (2014-11-22 (土) 03:59:58)
- 8 (2015-01-30 (金) 19:37:39)
- 9 (2015-03-17 (火) 19:10:39)
- 10 (2016-01-29 (金) 14:02:53)
- 11 (2016-05-26 (木) 15:38:26)
- 12 (2017-08-24 (木) 13:01:26)
- 13 (2018-04-18 (水) 20:52:01)
- 14 (2020-04-18 (土) 18:59:27)
- 15 (2021-10-20 (水) 16:21:17)
- 16 (2025-01-03 (金) 08:57:02)
- 17 (2025-01-03 (金) 09:01:23)
- 18 (2025-01-03 (金) 09:02:38)
- 19 (2025-01-03 (金) 09:03:21)
- 20 (2025-01-03 (金) 09:04:02)
- 21 (2025-06-19 (木) 12:41:37)
- 22 (2025-06-19 (木) 12:43:47)
 
- title: JTextFieldに透かし画像を表示する tags: [JTextField, Focus, ImageIcon] author: aterai pubdate: 2009-10-26T13:04:26+09:00 description: JTextFieldの文字列が空でフォーカスがない場合、透かし画像を表示するように設定します。
概要
JTextFieldの文字列が空でフォーカスがない場合、透かし画像を表示するように設定します。
Screenshot

Advertisement
サンプルコード
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 public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (showWatermark) {
      Graphics2D g2d = (Graphics2D) g.create();
      //Insets i = getMargin();
      Insets i = getInsets();
      int yy = (getHeight() - image.getIconHeight()) / 2;
      g2d.drawImage(image.getImage(), i.left, yy, this);
      g2d.dispose();
    }
  }
  @Override public void focusGained(FocusEvent e) {
    showWatermark = false;
    repaint();
  }
  @Override public void focusLost(FocusEvent e) {
    showWatermark = "".equals(getText().trim());
    repaint();
  }
}
解説
- 上
- 下
- JTextFieldの文字列が空で、フォーカスも無い場合、上記のように文字列ではなく、画像を表示します。
 
JTextFieldにフォーカスと文字列が無い場合の表示では、JPasswordFieldに応用できないので、以下のように透かし画像の表示と同じような方法で文字列を表示します。