The following example illustrates creating an AWT Choice. This tutorial will also cover all the core methods of the java.awt.Choice class.
Also see Creating ItemListener for AWT Choice
Next: Creating AWT List in Java
Previous: 5 Ways to Create an AWT Checkbox
import java.awt.*;
import java.awt.event.*;
class AWTChoice extends Frame
{
Choice c,h,r;
public AWTChoice()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Choice in AWT Example");
setLayout(new FlowLayout());
// First, create a choice
c=new Choice();
// Add items
c.add("Apple");
c.add("Mango");
c.add("Orange");
c.add("Grapes");
c.add("Strawberry");
c.add("Strawberry");
// Set a selected index, default is 0
c.select(2);
// Insert item at give index
c.insert("Guava",3);
// Remove the first Strawberry
c.remove("Strawberry");
// This is another choice
h=new Choice();
// Add items to h
h.addItem("Vanilla");
h.addItem("Chocolate");
h.addItem("Butterscotch");
h.addItem("Strawberry");
// Remove an item at given index
h.remove(2);
// Select Strawberry (case-senstive!!)
h.select("Strawberry");
// One more, last one!
r=new Choice();
// Add items
r.add("Item 1");
r.add("Item 2");
r.add("Item 3");
r.add("Item 4");
// Now, remove all!
r.removeAll();
// Add choices
add(c);
add(h);
add(r);
// Print get methods
System.out.println("Selected index in c "+c.getSelectedIndex());
System.out.println("Selected item in h "+h.getSelectedItem());
System.out.println("No.of items in r "+r.getItemCount());
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new AWTChoice();
}
}
Also see Creating ItemListener for AWT Choice
Next: Creating AWT List in Java
Previous: 5 Ways to Create an AWT Checkbox
No comments:
Post a Comment