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

#contents

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

#screenshot

**サンプルコード [#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(oColor);
           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();
         if("".equals(str)) {
           textField.setForeground(dColor);
           textField.setText(initMessage);
         }
       }
     });
   }
 }

-&jnlp;
-&jar;
-&zip;

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

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