---
category: swing
folder: TagInputPanel
title: JTextFieldで追加、JLabelで表示、JButtonで削除可能なタグ入力コンポーネントを作成する
title-en: Create a tag input component that can be added with a JTextField, displayed with a JLabel, and deleted with a JButton
tags: [JTextField, JLabel, JButton]
author: aterai
pubdate: 2026-01-26T01:05:58+09:00
description: JTextFieldでタグの追加、JLabelでタグの表示、JButtonでタグの削除を実行するタグ入力コンポーネントを作成します。
summary-jp: JTextFieldでタグの追加、JLabelでタグの表示、JButtonでタグの削除を実行するタグ入力コンポーネントを作成します。
summary-en: Create a tag input component that uses a JTextField to add tags, displays them with JLabels, and allows them to be deleted using JButtons.
image: https://drive.google.com/uc?id=1yVseoGx9LVdDqY7-gnNnoYDutsVSC3dG
---
* Summary [#summary]
JTextFieldでタグの追加、JLabelでタグの表示、JButtonでタグの削除を実行するタグ入力コンポーネントを作成します。
// #en{{Create a tag input component that uses a JTextField to add tags, displays them with JLabels, and allows them to be deleted using JButtons.}}
`JTextField`でタグの追加、`JLabel`でタグの表示、`JButton`でタグの削除を実行するタグ入力コンポーネントを作成します。
// #en{{Create a tag input component that uses a `JTextField` to add tags, displays them with `JLabel`s, and allows them to be deleted using `JButton`s.}}

#download(https://drive.google.com/uc?id=1yVseoGx9LVdDqY7-gnNnoYDutsVSC3dG)

* Source Code Examples [#sourcecode]
#code(link){{
class TagInputPanel extends JPanel {
  private final List<String> tags = new ArrayList<>();
  private final JTextField textField = new JTextField(15);
  private final JPanel tagContainer = new JPanel(new FlowLayout(FlowLayout.LEFT)) {
    @Override public void updateUI() {
      super.updateUI();
      setBackground(UIManager.getColor("TextField.background"));
    }
  };

  protected TagInputPanel() {
    super(new BorderLayout());
    textField.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    textField.addActionListener(e -> {
      String text = textField.getText().trim();
      if (!text.isEmpty() && !tags.contains(text)) {
        addTag(text);
        textField.setText("");
      }
    });
    textField.addKeyListener(new KeyAdapter() {
      @Override public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE &&
            textField.getText().isEmpty()) {
          removeLastTag();
          e.consume();
        }
      }
    });
    tagContainer.add(textField);
    add(new JScrollPane(tagContainer));
  }

  @Override public void updateUI() {
    super.updateUI();
    setBorder(UIManager.getBorder("TextField.border"));
    setBackground(UIManager.getColor("TextField.background"));
  }

  private void addTag(String text) {
    JPanel tag = new JPanel(new BorderLayout(5, 0));
    tag.setName(text);
    tag.setBackground(new Color(230, 245, 255));
    Color color = UIManager.getColor("Table.selectionBackground");
    tag.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(color),
        BorderFactory.createEmptyBorder(3, 5, 3, 5)
    ));
    tags.add(text);
    tag.add(new JLabel(text));
    tag.add(makeCloseButton(tag), BorderLayout.EAST);
    tagContainer.add(tag, tagContainer.getComponentCount() - 1);
    resizeAndRepaint();
  }

  private JButton makeCloseButton(JPanel tag) {
    JButton closeBtn = new JButton("×") {
      @Override public void updateUI() {
        super.updateUI();
        setContentAreaFilled(false);
        setFocusPainted(false);
        setFocusable(false);
        setBorder(BorderFactory.createEmptyBorder());
      }
    };
    closeBtn.addActionListener(e -> {
      tags.remove(tag.getName());
      tagContainer.remove(tag);
      resizeAndRepaint();
    });
    closeBtn.addMouseListener(new MouseAdapter() {
      @Override public void mouseEntered(MouseEvent e) {
        e.getComponent().setForeground(Color.RED);
      }

      @Override public void mouseExited(MouseEvent e) {
        e.getComponent().setForeground(UIManager.getColor("Button.foreground"));
      }
    });
    return closeBtn;
  }

  private void removeLastTag() {
    int count = tagContainer.getComponentCount();
    boolean moreThanOne = count > 1;
    if (moreThanOne) {
      tags.remove(tags.size() - 1); // Java 21: .removeLast();
      tagContainer.remove(count - 2);
      resizeAndRepaint();
    }
  }

  // ...
}
}}

* Description [#description]
- タグコンポーネントは`new JPanel(new BorderLayout(5, 0))`で作成した`JPanel`の中央にタグ文字列用の`JLabel`、`BorderLayout.EAST`に削除用の`JButton`を配置して作成
- これらのタグコンポーネントを左揃えで配置するよう`new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5))`でタグ配置コンテナを作成
- `EmptyBorder`で枠線を非表示にしてタグ入力用の`JTextField`を作成
-- `JTextField`に`ActionListener`を追加しKBD{Enter}キーでタグ追加アクションと`JTextField`のクリアを実行
-- `JTextField`に`KeyListener`を追加しKBD{BackSpace}キーで末尾タグの削除と`beep`音のキャンセルを実行
- タグ配置コンテナに`ContainerListener`を追加し、タグ追加で`componentAdded`、タグ削除で`componentRemoved`が実行されると現在のタグ一覧をカンマ区切りでログ出力

#code{{
JTextArea log = new JTextArea();
TagInputPanel tagInput = new TagInputPanel();
tagInput.getTagContainer().addContainerListener(new ContainerListener() {
  @Override public void componentAdded(ContainerEvent e) {
    log.setText(String.join(", ", tagInput.getTags()));
  }

  @Override public void componentRemoved(ContainerEvent e) {
    log.setText(String.join(", ", tagInput.getTags()));
  }
});
}}

* Reference [#reference]
- [[JTabbedPaneにタブを閉じるボタンを追加>Swing/TabWithCloseButton]]

* Comment [#comment]
#comment
#comment