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

#contents

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

#screenshot

**サンプルコード [#lf2627f8]
#code{{
 class GhostFocusListener implements FocusListener {
   private final String initMessage = "文字列を入力してください";
   private final Color dColor = UIManager.getColor("TextField.inactiveForeground");
   private final Color oColor = UIManager.getColor("TextField.foreground");
   public GhostFocusListener(final JTextComponent tf) {
     tf.setForeground(dColor);
     tf.setText(initMessage);
   }
   public void focusGained(final FocusEvent e) {
     JTextComponent textField = (JTextComponent)e.getSource();
     String str = textField.getText();
     Color col  = textField.getForeground();
     if(initMessage.equals(str) && dColor.equals(col)) {
       textField.setForeground(oColor);
       textField.setText("");
     }
   }
   public void focusLost(final FocusEvent e) {
     JTextComponent textField = (JTextComponent)e.getSource();
     String str = textField.getText().trim();
     if("".equals(str)) {
       textField.setForeground(dColor);
       textField.setText(initMessage);
     }
   }
 }
}}
-&jnlp;
-&jar;
-&zip;

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

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