想实现comboBox_1根据comboBox所选内容而改变,所以对comboBox加了监听,在监听中给comboBox_1添加选项,但是这样的话在获取comboBox_1被选中的选项时就会报空指针异常,无法获取。请问有什么解决办法吗?
static String TextWorkMa2=null;
static String TextVol=null;
final JComboBox comboBox = new JComboBox();
comboBox.addItem("请选择工件材料");
comboBox.addItem("铝");
comboBox.addItem("铝合金");
comboBox.addItem("钛,钛合金");
comboBox.addItem("铁类材料");
comboBox.addItem("铜");
comboBox.addItem("锌");
comboBox.addItem("碳钢,低合金钢,不锈钢");
getContentPane().add(comboBox, "cell 3 4,growx");
final JComboBox comboBox_1 = new JComboBox();
comboBox_1.addItem("请选择管电压");
comboBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if((comboBox.getSelectedItem()).toString()=="铝"||comboBox.getSelectedItem().toString()=="铝合金"){
comboBox_1.removeAllItems();
comboBox_1.addItem("请选择管电压");
comboBox_1.addItem("100kV");
comboBox_1.addItem("150kV");
comboBox_1.addItem("220kV");
}if(comboBox.getSelectedItem().toString()=="钛,钛合金"){
comboBox_1.removeAllItems();
comboBox_1.addItem("请选择管电压");
comboBox_1.addItem("150kV");
comboBox_1.addItem("220kV");
comboBox_1.addItem("400kV");
comboBox_1.addItem("1MeV");
comboBox_1.addItem("2MeV");
comboBox_1.addItem("4-25MeV");
} if(comboBox.getSelectedItem().toString()=="铁类材料"||comboBox.getSelectedItem().toString()=="碳钢,低合金钢,不锈钢"||comboBox.getSelectedItem().toString()=="铜"){
comboBox_1.removeAllItems();
comboBox_1.addItem("请选择管电压");
comboBox_1.addItem("100kV");
comboBox_1.addItem("150kV");
comboBox_1.addItem("220kV");
comboBox_1.addItem("400kV");
comboBox_1.addItem("1MeV");
comboBox_1.addItem("2MeV");
comboBox_1.addItem("4-25MeV");
}if(comboBox.getSelectedItem().toString()=="锌"){
comboBox_1.removeAllItems();
comboBox_1.addItem("请选择管电压");
comboBox_1.addItem("150kV");
comboBox_1.addItem("220kV");
comboBox_1.addItem("400kV");
}
TextWorkMa2=(comboBox.getSelectedItem()).toString();
}
});
comboBox_1.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
System.out.println(TextVol);
TextVol=(comboBox_1.getSelectedItem()).toString();
}
});
------解决思路----------------------
comboBox_1.removeAllItems();
comboBox_1.addItem("请选择管电压");
comboBox这些都会触发 comboBox_1监听器,所以你在removeAllItems()调用后会引起空指针异常
既然会触发,那么你就得判断是不是空指针了,如果不是再做出反应
另外监听器我觉得用ActionListener更好
毕竟你那个仅仅是做出改动时才触发
万一我选择的是同一个选项呢?
comboBox_1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object object = comboBox_1.getSelectedItem();
if (object != null) {
TextVol = object.toString();
System.out.println(TextVol);
}
}
});