Tuesday, November 4, 2008

ChoiceApplet

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

public class ChoiceApplet extends Applet{
public void init(){

Choice myOption = new Choice();

myOption.addItem("Red");
myOption.addItem("Green");
myOption.addItem("Blue");
myOption.addItem("Yellow");

//Add choice to applet
add(myOption);

ItemListener myListener = new ChoiceItemListener(this);

//add listener to the Choice
myOption.addItemListener(myListener);

}

}


class ChoiceItemListener implements ItemListener{
Component component;

public ChoiceItemListener(Component component){
this.component=component;
}

public void itemStateChanged(ItemEvent event){
if (event.getStateChange() == ItemEvent.SELECTED) {
String itemLabel = (String)event.getItem();

if (itemLabel=="Red") setColor(Color.red);
if (itemLabel=="Blue") setColor(Color.blue);
if (itemLabel=="Green") setColor(Color.green);
if (itemLabel=="Yellow") setColor(Color.yellow);
}
}

public void setColor(Color color){
component.setBackground(color);
component.repaint();
}
}