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

#contents

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

#screenshot

**サンプルコード [#rc7f0af2]
 JLabel label = new JLabel(image);
 label.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
 label.setBorder(null);
 label.setBounds(1,1,image.getIconWidth(),image.getIconHeight());
 Insets m  = field01.getMargin();
 Insets m2 = new Insets(m.top,m.left+image.getIconWidth(),m.bottom,m.right);
 field01.setMargin(m2);
 field01.add(label);

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

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

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

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

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

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

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