TITLE:JTextField内にアイコンを追加
#navi(../)
*JTextField内にアイコンを追加 [#h496664d]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-01-03~
更新日:&lastmod;

#contents

**概要 [#xfd25592]
JTextFieldの内部にアイコンを表示します。

#screenshot

**サンプルコード [#rc7f0af2]
#code{{
 int w = image.getIconWidth();
 int h = image.getIconHeight();
 JLabel label = new JLabel(image);
 label.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
 label.setBorder(null);
 label.setBounds(1,1,w,h);
 Insets m = field.getMargin();
 field.setMargin(new Insets(m.top,m.left+w,m.bottom,m.right));
 field.add(label);
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#z9fc33ce]
サンプルではsetMarginでJTextFieldの左に余白を作り、そこにJLabelを配置することでアイコンを表示しています。

[[JComboBoxにアイコンを追加>Swing/IconComboBox]]のように、Borderを使っても同様のことができますが、JTextComponentを継承したコンポーネントでは、setMarginを使用するとカーソルの指定などが簡単にできるのでおすすめです。

また、JLabelの代わりに、JButtonなどを置くこともできます(参考リンクを参照)。

JComboBoxのEditorを取得してMarginを指定しても、なぜかうまくいきません。
#code{{
 JTextField field = (JTextField) combo02.getEditor().getEditorComponent();
}}

**参考リンク [#g5b06829]
-[[Add a clickable icon to the left corner of a JTextField>http://forum.java.sun.com/thread.jspa?threadID=454437]]
-[[JTextFieldのMarginを設定する>Swing/TextFieldMargin]]
-[[JComboBoxにアイコンを追加>Swing/IconComboBox]]

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