Tuesday, 20 January 2015

Tutorial on JCombo Box in java

The following example contains a combo box and a label.The label displays an icon the combo box contain name of languages when user select any language its picture will be  displayed on a label.

JCOMBO BOX IN JAVA:

JCombo box is a simple drop down list through JCOMBOBOX class.Normally it contain only one entry its constructor are shown here

JComboBox()

This constructor creates a simple JComboBox with no items in it.

JComboBox(Vector v)

This constructor is used to create  that contain element in the specified vector.

JComboBox(ComboBoxModel)

With the help of this constructor we can create a combo box from specified combo box model.This constructor does not create default combo box model.

JComboBox(Object[])


This constructor creates combo box that contain items in the specified array.

WHY WE USE ADDITEM:

Combobox does not have item if we want to add in combobox we have to use addItem as shown in this tutorial its signature is shown here
void addItem(Object obj) 

CODING:

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

class tab extends JFrame
implements ItemListener {
JLabel j1;
tab()
{
super();
setTitle("J Combo");
setSize(250, 300);
setVisible(true);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);    
JComboBox jc = new JComboBox();
jc.addItem("java");
jc.addItem("c#");
jc.addItem("C++");
j1 =new JLabel(new ImageIcon("blank.png"));
FlowLayout f=new FlowLayout();
setLayout(f);
add(jc);
add(j1);
jc.addItemListener(this);


}
public void itemStateChanged(ItemEvent ie){
String s=(String)ie.getItem();
j1.setIcon(new ImageIcon(s+".png"));

}

}
class comb
{
public static void main(String args[])
{
tab x= new tab();
}
}

OUTPUT:



2 comments: