Swing/WatermarkInTextField のバックアップ差分(No.14)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - 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)
- 追加された行はこの色です。
- 削除された行はこの色です。
---
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
---
* 概要 [#summary]
`JTextField`の文字列が空でフォーカスがない場合、透かし画像を表示するように設定します。
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTWh1Qjh4I/AAAAAAAAApY/bLarzjLy7-8/s800/WatermarkInTextField.png)
* サンプルコード [#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();
}
}
}}
* 解説 [#explanation]
- 上
-- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]
- 下
-- `JTextField`の文字列が空でフォーカスも無い場合、文字列ではなく画像を表示
* 参考リンク [#reference]
- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]
- [[JPasswordFieldにヒント文字列を描画する>Swing/InputHintPasswordField]]
-- [[JTextFieldにフォーカスと文字列が無い場合の表示>Swing/GhostText]]の方法は`JPasswordField`に応用できないので、`JLabel`を配置することでヒント文字列を表示
- [[JComboBoxでアイテムが選択されていない場合のプレースホルダ文字列を設定する>Swing/ComboBoxPlaceholder]]
* コメント [#comment]
#comment
#comment