Credits

Sunday, February 20, 2011

Java's Combo Box

A Java's combo box appears like a list but with drop down collection of items. You can actually type in a combo box or simply select an item from the options.

A constructor for a combo box can be without parameters or with a string of items as stated below:

String[] courses = {"Computer Science"," Information System", "Information Technology"}
 JComboBox  courselist = new JComboBox(courses);

If your constructor is without parameters,  JComboBox  courselist = new JComboBox(  );, you can add the items using the addItem( ) method as stated below:

courselist.addItem("Computer Science");
courselist.addItem("Information System");
courselist.addItem("Information Technology");

 You can use the method getSelectedItem( ) to  return selected option. See the sample below for complete sample program.


[+/-] show/hide

import javax.swing.*;
import java.awt.*;

public class ComboBoxes extends JFrame {
public ComboBoxes() {
super("Combo Boxes");
setSize(345, 120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox profession = new JComboBox();
FlowLayout flo = new FlowLayout();
profession.addItem("Butcher");
profession.addItem("Baker");
profession.addItem("Candlestick maker");
profession.addItem("Fletcher");
profession.addItem("Fighter");
profession.addItem("Technical writer");
setLayout(flo);
add(profession);
setVisible(true);
}

public static void main(String[] arguments) {
ComboBoxes app = new ComboBoxes();
}
}

AddThis