Akshat Jain Akshat Jain - 1 month ago 6
Java Question

It Runs First Time while loading the frame but when i choose the secound item it gives me error

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {

jComboBox1.revalidate();
jComboBox2.removeAllItems();
jComboBox3.removeAllItems();
jComboBox4.removeAllItems();
String b1=jComboBox1.getSelectedItem().toString();
String bb=this.branch;
String y1=this.year;
if(y1!=null){
String[] b=y1.split(";");
System.out.println(y1);
System.out.println(b1);
int size=b.length;
System.out.println(size);
for(int i=0;i<size;i++){
if(b[i].matches("(?i).*"+b1+".*")){
System.out.println(b[i]);
jComboBox2.addItem(b[i].replaceAll(":","").replaceAll(b1.toLowerCase(), ""));
jComboBox2ActionPerformed( evt);
}}}
}


It Runs First Time while loading the frame but when i choose the secound item it gives me error

Answer Source

Once you apply removeAllItems then there is no item in combo-box

so getSelectedItem internally use the ComboBoxModel getSelectedItem function which states

The selected item or null if there is no selection

although oracle docs doesn't state anything about returning null

solution : you get null and toString() in null cause you the nullpointer exception so make sure you have some items when you call getSelectedItem or put a nullity check

String b1=jComboBox1.getSelectedItem()!=null ? jComboBox1.getSelectedItem().toString(): "";