«Back to Home

Core Java

Topics

JComboBox Class In Java

JComboBox Class
 
In Java, JComboBox class creates the combobox and only one item can be selected from the item list at a time.
 
Constructors of JComboBox class
  • JComboBox()

  • JComboBox(Object[] items)

  • JComboBox(Vector<?> items)
Methods of JComboBox class

public void addItem(Object anObject)

This method is used to add an item to the item list.
 
public void removeItem(Object anObject)

This method is used to delete an item from the item list.
 
public void removeAllItems()

This method is used to remove all the items from the list.
 
public void setEditable(boolean b)

This method is used to determine whether the JComboBox is editable or not.
 
public void addActionListener(ActionListener a)

This method is used to add the ActionListener.
 
public void addItemListener(ItemListener i)

This method is used to add the ItemListener.
 
Let’s see an example of JcomboBox class, given below.
 
Code
  1. import javax.swing.*;  
  2. public class JcomboBoxExample {  
  3.     JFrame jf;  
  4.     JcomboBoxExample() {  
  5.         jf = new JFrame("ComboBox Example");  
  6.         String animals[] = {"Cow""Dog""Cat""Rat""Pig"};  
  7.         JComboBox cb = new JComboBox(animals);  
  8.         cb.setBounds(50509020);  
  9.         jf.add(cb);  
  10.         jf.setLayout(null);  
  11.         jf.setSize(400400);  
  12.         jf.setVisible(true);  
  13.     }  
  14.     public static void main(String[] args) {  
  15.         new JcomboBoxExample();  
  16.     }  
  17. }  
38

Output

39
 
Summary

Thus, we learnt that the JComboBox class creates the combobox and only one item can be selected from the item list at a time only and also learnt how to use it in Java.