JComboBox - See this example to know what's inside the box?

What is JComboBox?


Nothing, it is just son of Choice in the AWT. Son doesn't mean that it is the sub class of Choice, instead i just mean that it does the same thing as the Choice in the AWT does. It allows only one item to choose. Mostly used to check Male/Female, Date of Birth (Day-Month-Year) etc.

The Example







import javax.swing.*;
import java.awt.*;
class JComboBoxExample extends JFrame
{
JComboBox jc1,jc2;
public JComboBoxExample()
{

setTitle("I am JComboBox Example!");
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jc1=new JComboBox();

// Add items
jc1.addItem("Google");
jc1.addItem("Yahoo!");
jc1.addItem("Bing");
jc1.addItem("iGo4iT Search");

// Set 4th item selected
jc1.setSelectedIndex(3);

// Add jc1 to JFrame
add(jc1);

jc2=new JComboBox();

// Add items
jc2.addItem("Amazon.com");
jc2.addItem("eBay");
jc2.addItem("Walmart");
jc2.addItem("Best Buy");

// Make it editable
jc2.setEditable(true);

// Add jc to JFrame
add(jc2);

}

public static void main(String args[])
{
new JComboBoxExample();
}
}

Explanation


jc1,jc2: Both are the objects for the JComboBox.

addItem(""): Method of the JComboBox used to add items to it. The parameter to it is usually java.lang.Object, as per the requirement i have used String as it is a sub class of java.lang.Object class.

jc1.setSelectedIndex(3): As we know, index usually start from 0. Setting the selected index as 3 means that select the 4th item (0 1 2 3). Therefore, iGo4iT Search is selected.

jc2.setEditable(true): You might have observed, some drop downs can be edited i.e. the user is allowed to type something in it usually in autocomplete. It is obvious now i hope so, that the by passing true to the method lets the user type something in the JComboBox.