TITLE:JTextField内にアイコンを追加

JTextField内にアイコンを追加

編集者:Terai Atsuhiro
作成日:2005-01-03
更新日:2021-05-21 (金) 03:22:02

概要

JTextFieldの内部にアイコンを表示します。

#screenshot

サンプルコード

ImageIcon image = new ImageIcon(getClass().getResource("16x16.png"));
int w = image.getIconWidth();
int h = image.getIconHeight();

JTextField field = new JTextField("bbbbbbbbbb");
Insets m = field.getMargin();
field.setMargin(new Insets(m.top, m.left+w, m.bottom, m.right));

JLabel label = new JLabel(image);
label.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
label.setBorder(null);
label.setBounds(m.left, m.top, w, h);

field.add(label);
  • &jnlp;
  • &jar;
  • &zip;

解説

サンプルではsetMarginでJTextFieldの左に余白を作り、そこにJLabelを配置することでアイコン(画像)を表示しています。

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

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

JComboBoxのEditorを取得してMarginを指定しても、なぜかうまくいきません。

JTextField field = (JTextField) combo02.getEditor().getEditorComponent();

参考リンク

コメント