Java Swing How to - Add items runtime on JComboBox








Question

We would like to know how to add items runtime on JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from w w  w .j ava  2s .c  o  m
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComboBox<String> comboBox = new JComboBox<>(new String[] { "Something",
        "Stuff", "Beep" });
    JButton add = new JButton("Add item");
    add.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        comboBox.addItem("Item");
      }
    });
    frame.add(comboBox);
    frame.add(add, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
  }
}