• 追加された行はこの色です。
  • 削除された行はこの色です。
---
category: swing
folder: FocusColor
title: JTextFieldにフォーカスがある場合の背景色を設定
tags: [JTextField, FocusListener]
author: aterai
pubdate: 2006-08-07T16:37:20+09:00
description: どのJTextFieldを編集しているのかを分かりやすくするために、フォーカスのあるJTextFieldの背景色を変更します。
image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTM__NmYpI/AAAAAAAAAaE/EUMDKR-Rwa4/s800/FocusColor.png
---
* 概要 [#rfb552fd]
* 概要 [#summary]
どの`JTextField`を編集しているのかを分かりやすくするために、フォーカスのある`JTextField`の背景色を変更します。

#download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTM__NmYpI/AAAAAAAAAaE/EUMDKR-Rwa4/s800/FocusColor.png)

* サンプルコード [#eb0e7a99]
* サンプルコード [#sourcecode]
#code(link){{
private static class BGFocusListener implements FocusListener {
  private final Color dColor;
  private final Color oColor;
  public BGFocusListener(Color oColor, Color dColor) {
    this.dColor = dColor;
    this.oColor = oColor;
  }
  @Override public void focusGained(final FocusEvent e) {
    ((JTextField)e.getSource()).setBackground(dColor);
    ((JTextField) e.getSource()).setBackground(dColor);
  }
  @Override public void focusLost(final FocusEvent e) {
    ((JTextField)e.getSource()).setBackground(oColor);
    ((JTextField) e.getSource()).setBackground(oColor);
  }
}
}}

* 解説 [#rb40a9f5]
* 解説 [#explanation]
`JTextField`に`FocusListener`を追加することで、`focusGained`、`focusLost`した場合にそれぞれ背景色を変更しています。

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