#navi(../)
*JTextFieldにフォーカスと文字列が無い場合の表示 [#m17af070]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-11-07~
更新日:&lastmod;

#contents

**概要 [#x4cf9b94]
JTextFieldにフォーカスと文字列が無い場合、薄い色でその説明を表示します。

http://terai.xrea.jp/swing/ghosttext/screenshot.png

**サンプルコード [#lf2627f8]
 class GhostFocusListener implements FocusListener {
   private final String initMessage = "文字列を入力してください";
   private final Color dColor = SystemColor.inactiveCaptionText;
   private final Color oColor;
   public GhostFocusListener(final JTextComponent tf) {
     oColor = tf.getForeground();
     tf.setForeground(dColor);
     tf.setText(initMessage);
   }
   public void focusGained(final FocusEvent e) {
     SwingUtilities.invokeLater(new Runnable() {
       public void run() {
         JTextComponent textField = (JTextComponent)e.getSource();
         String str = textField.getText();
         Color col  = textField.getForeground();
         if(initMessage.equals(str) && dColor.equals(col)) {
           textField.setForeground(Color.black);
           textField.setText("");
         }
       }
     });
   }
   public void focusLost(final FocusEvent e) {
     SwingUtilities.invokeLater(new Runnable() {
       public void run() {
         JTextComponent textField = (JTextComponent)e.getSource();
         String str = textField.getText().trim();
         Color col  = textField.getForeground();
         if(str.equals("")) {
           textField.setForeground(dColor);
           textField.setText(initMessage);
         }
       }
     });
   }
 }

-[[サンプルを起動>http://terai.xrea.jp/swing/ghosttext/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/ghosttext/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/ghosttext/src.zip]]

**解説 [#r832c3b6]
上記のサンプルでは、下のJTextFieldからフォーカスが失われた時、まだ何も入力されていない場合は、そのJTextFieldの説明などを薄く表示することができるようにしています。

//**参考リンク
**コメント [#h0951933]
#comment