Java AWT Tutorials

adplus-dvertising
Handling Choice Box in java
Previous Home Next

In this example we are going to handle Choice Box. To control the Choice Box we are using three type of package. One is java.awt.* second is java.applet.* and third is java.awt.event.*; .The java.awt.* is used for GUI interface. AWT classes are contain in this package. The java.applet.* package is used to create an applet and java.awt.event.*; defined within the java.awt.*; package is a subclass of EventObject. It is a super class of all AWT-based event.

The Choice class is used to create a pop-up list of items from which the user may choose. A choice control is a form of menu. Each item in a list is a string that appears as a left-justified label in the order it is add to the choice object.To add a selection to the list, call add().

void add(string name);

In our example first we implement two interface:

ItemListener(): Each listener implement the ItemLinstner.

itemStateChange(): When a option is selected or an event is occur this interface is called.

To deterrmine which item is currently selected,you may call : String getSelectedItem(); It returns a string containing the name of the item. or int getSelectedIndex(); It return the index of the item.

To obtain the number of item in the list call:

int getItemCount();

In our example we create two choice menu one is country and other is city.

Example

//Choice
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceDemo" width=300 height=200>
</applet>
*/
public class ChoiceDemo extends Applet implements ItemListener {
Choice country,city;
String msg="";
public void init(){
country = new Choice();
city = new Choice();
country.add("India");
country.add("Rusia");
country.add("Pakistan");
country.add("Srilanka");
city.add("unnao");
city.add("Lucknow"); 
city.add("Lahour"); 
city.add("Kuvait");
city.select("Caindy");
add(country);
add(city);
country.addItemListener(this);
city.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie){
repaint();
}
public void paint(Graphics g){
msg="Your country name is:";
msg+=country.getSelectedItem();
g.drawString(msg,6,120);
msg="your city name is:";
msg += city.getSelectedItem();
g.drawString(msg,6,140);
}
}

Output Of Example:

Download Source Code

Previous Home Next