Add or Remove an item in a JComboBox

In JCombobox the selected text is displayed in the text field.The Swing JCombo will automatically add scroll bar.  combo_b.removeItemAt(0) is used to remove elements (specified item) from the list.

 

import javax.swing.*;

import java.awt.event.*;

public class AddRemoveItemCombo

{

  JComboBox combo_b;

  JTextField txBox;

  public static void main(String[] aaa)

{

  AddRemoveItemCombo ar = new AddRemoveItemCombo();

  }

  public AddRemoveItemCombo()

{

  JFrame j_frame = new JFrame("Add&Remove Items of a Combo Box");

  String items[] = {"Java", "JSP", "PHP", "C", "C++","Dot Net","Oracle"};

  combo_b = new JComboBox(items);

  JButton button1 = new JButton("Add");

  txBox = new JTextField(20);

  button1.addActionListener(new ActionListener()

{

  public void actionPerformed(ActionEvent acte)

{

  if (!txBox.getText().equals(""))

{

  int a = 0;

  for(int i = 0; i < combo_b.getItemCount(); i++)

{

  if(combo_b.getItemAt(i).equals(txBox.getText()))

{

  a = 1;

  break;

  }

  }

  if (a == 1)

 JOptionPane.showMessageDialog(null,"Combo has already this item.");

  else

  combo_b.addItem(txBox.getText());

  }

  else

{

  JOptionPane.showMessageDialog(null,"Pls enter text in Text Box");

  }

  }

  });

  JButton button2 = new JButton("Remove");

  button2.addActionListener(new ActionListener()

{

  public void actionPerformed(ActionEvent acte)

{

  if (combo_b.getItemCount() > 0)

  combo_b.removeItemAt(0);

  else

  JOptionPane.showMessageDialog(null,"Sorry!Item not available");

  }

  });

  JPanel panel = new JPanel();

  JPanel panel1 = new JPanel();

  panel.add(txBox);

  panel.add(combo_b);

  panel.add(button1);

  panel.add(button2);

  j_frame.add(panel);

//  frame.add(panel1);

  j_frame.setSize(400, 400);

  j_frame.setVisible(true);

 

  }

}

Output....

add or remove item in combo