• title: JTextField内にアイコンを追加 tags: [JTextField, ImageIcon, JLabel, Border] author: aterai pubdate: 2005-01-03 description: JTextFieldの内部に余白を生成し、そこにImageIconを設定したJLabelを配置します。

概要

JTextFieldの内部に余白を生成し、そこにImageIconを設定したJLabelを配置します。

サンプルコード

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(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
label.setBorder(null);
label.setBounds(m.left, m.top, w, h);

field.add(label);
View in GitHub: Java, Kotlin

解説

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

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

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


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


JTextFieldの右端にJLabelを置く場合は、以下のようにSpringLayoutを使用する方法があります。

final JLabel label2 = new JLabel(image);
label2.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
label2.setBorder(BorderFactory.createEmptyBorder());
JTextField field2 = new JTextField("ccccccccccccccccccccccccccc") {
  @Override public void updateUI() {
    super.updateUI();
    removeAll();
    SpringLayout l = new SpringLayout();
    setLayout(l);
    Spring fw = l.getConstraint(SpringLayout.WIDTH,  this);
    Spring fh = l.getConstraint(SpringLayout.HEIGHT, this);
    SpringLayout.Constraints c = l.getConstraints(label2);
    c.setConstraint(SpringLayout.WEST,  fw);
    c.setConstraint(SpringLayout.SOUTH, fh);
    add(label2);
  }
};
m = field2.getMargin();
field2.setMargin(new Insets(m.top + 2, m.left, m.bottom, m.right + w));

参考リンク

コメント