TITLE:JTextFieldにフォーカスと文字列が無い場合の表示
#navi(../)
RIGHT:Posted by [[terai]] at 2005-11-07
*JTextFieldにフォーカスと文字列が無い場合の表示 [#m17af070]
JTextFieldにフォーカスが無く文字列が空の場合、薄い色でその説明を表示します。

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

#screenshot

**サンプルコード [#lf2627f8]
#code{{
class HintTextFocusListener implements FocusListener {
  Color INACTIVE_COLOR = UIManager.getColor("TextField.inactiveForeground");
  Color ORIGINAL_COLOR = UIManager.getColor("TextField.foreground");
  private final String hintMessage;
  public HintTextFocusListener(final JTextComponent tf) {
    hintMessage = tf.getText();
    tf.setForeground(INACTIVE_COLOR);
  }
  public void focusGained(final FocusEvent e) {
    JTextComponent textField = (JTextComponent)e.getSource();
    String str = textField.getText();
    Color col  = textField.getForeground();
    if(hintMessage.equals(str) && INACTIVE_COLOR.equals(col)) {
      textField.setForeground(ORIGINAL_COLOR);
      textField.setText("");
    }
  }
  public void focusLost(final FocusEvent e) {
    JTextComponent textField = (JTextComponent)e.getSource();
    String str = textField.getText().trim();
    if("".equals(str)) {
      textField.setForeground(INACTIVE_COLOR);
      textField.setText(hintMessage);
    }
  }
}
}}

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

**参考リンク [#o0c01026]

-[[JTextFieldに透かし画像を表示する>Swing/WatermarkInTextField]]

**コメント [#h0951933]
#comment