How to add or remove an item in a JComboBox component?

Lets see how to add and remove an item in JComboBox component.
There is a method called addItem() to add an item, to insert item at particular location there is a method called insertItemAt methods , for removal removeItemAt and removeAllItems methods can be used. Lets see how we can use these methods :


String[] menus = {"menu1", "menu2","menu3"};
JComboBox cmbMenus = new JComboBox(menus);


// Method to add item to combo box, item will get added at the end of list.
cmbMenus.addItem("menu3");

// insertItemAt allows item to be added to specific index.
cmbMenus.insertItemAt("menu0", 0);

cmbMenus.insertItemAt("menu1", 1);

// removeItemAt allows to remove item at specified index.
cmbMenus.removeItemAt(0);

cmbMenus.removeItemAt(cmbMenus.getItemCount()-1);

// removeAllItems is used to remove all items
cmbMenus.removeAllItems();
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

1 comments: