package applet;
import java.awt.*;
import java.awt.event.*;
//背景为什么没有变化?
public class MyChoice extends Frame implements TextListener {
Choice chc=new Choice();
//实例化
public MyChoice(){
setTitle("A new Choice!");
chc.add("yellow");
chc.add("orange");
chc.add("red");
setSize(200,150);
add(chc);
setVisible(true);
chc.addItemListener((ItemListener)this);
}
public void textValueChanged(TextEvent e){
if(chc.getSelectedItem()=="yellow"){
this.setBackground(Color.yellow);
}
else if(chc.getSelectedItem()=="orange"){
this.setBackground(Color.orange);
}
else {
this.setBackground(Color.red);
}
}
public static void main(String args[]){
new MyChoice();
}
}
----------------解决方案--------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
public class MyChoice extends Frame{
Choice chc=new Choice();
Container container;
public MyChoice(){
container=this;
setTitle("A new Choice!");
chc.add("yellow");
chc.add("orange");
chc.add("red");
setSize(200,150);
add(chc);
setVisible(true);
chc.addItemListener(new MyListener());
}
class MyListener implements ItemListener
{
public void itemStateChanged(ItemEvent e){
if(chc.getSelectedItem().equals("yellow")){
container.setBackground(Color.yellow);
}
else if(chc.getSelectedItem().equals("orange")){
container.setBackground(Color.orange);
}
else {
container.setBackground(Color.red);
}
}
}
public static void main(String args[]){
new MyChoice();
}
}
----------------解决方案--------------------------------------------------------