Skip to main content

Choice Box in Java


ChoiceBox
                    It is GUI component with DropDownlist of Item. User can select any item from list. it is Defined in the java.awt package. To Create Choice just create object of class choisebox and to add list item use add method. 
The ItemListerner interface is implemented in the class the choicebox is that was declared. To choicebox  enable with addItemListener to response to user.  Whenever user select an item from choice itemStateChanged(ItemEvent ie) is called.
Here Sample code with Explanation.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

//<applet code="choicemsg" width=200 height=200></applet>

public class choicemsg extends Applet implements ItemListener
{
            Choice ChoOS,ChoLang;
            String msg="";
            public void init()
            {
                        ChoOS=new Choice();
                        ChoLang=new Choice();
                        ChoOS.add("Windows 98");
                        ChoOS.add("Windows XP");
                        ChoOS.add("Windows Seven");
                        
                        ChoLang.add("C++");
                        ChoLang.add("JAVA");
                        ChoLang.add("VB");
                        add(ChoOS);
                        add(ChoLang);
                        ChoOS.addItemListener(this);
                        ChoLang.addItemListener(this);
            }
            public void itemStateChanged(ItemEvent ie)
            {
                        repaint();
            }
            public void paint(Graphics g)
            {
                        msg="Current OS : ";
                        msg+=ChoOS.getSelectedItem();
                        g.drawString(msg,30,100);
                        msg="Current Language : ";
                        msg+=ChoLang.getSelectedItem();
                        g.drawString(msg,30,120);
            }
}

Output
stunextstunext

 In the aboveprogram  two Choice ChoOS,ChoLang was created. We add choice item using  ChoOS.add method. When user select an from choice item, ItemListener event is raised and corresponding method itemStateChanged  is called. It that methods normally we write coding how handle that event.

Comments