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

Posted by at 2005-01-03

JTextField内にアイコンを追加

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

  • &jnlp;
  • &jar;
  • &zip;
IconTextField.png

サンプルコード

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));

参考リンク

コメント