import java.awt.*;
import java.awt.event.*;class SelectControl extends Frame implements ItemListener{
Choice tool;
List lst;


public SelectControl(){
super("测试");
Choice tool=new Choice();
List lst=new List();
setLayout(new FlowLayout());
tool.addItem("水果");
tool.addItem("蔬菜");
add(tool);
add(lst);
tool.addItemListener(this);
setSize(300,200);
setVisible(true);
lst.addItem("en");



public void shuiguo()
{
System.out.println("shuiguo");


}

public void itemStateChanged(ItemEvent ae){
  if(ae.getItem()=="水果"){
/* this.lst.removeAll();
this.lst.addItem("苹果");
    this.lst.add("西瓜");*/
  shuiguo();
}
/*else if(ae.getItem()=="蔬菜"){
this.lst.removeAll();
this.lst.add("青菜");
this.lst.add("花菜");
}*/
}

public static void main(String []args){
new SelectControl();
}
}

解决方案 »

  1.   

    你意思是你注释掉的那一段为什么会抛出异常是吗?
    Choice tool=new Choice();
    List lst=new List();
    把这两句改成
    tool=new Choice();
    lst=new List();
    就可以了
    Choice tool=new Choice();List lst=new List();
    执行的时候是重新生成一个新的对象,而不是初始化你的类的成员变量
    所以你得类的成员变量并没有初始化只是一个空指针,自然在下面引用的时候会抛出NullPointerException了