它在加载框架时第一次运行但是当我选择第二个项目时它给我错误

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);
            }}}
    } 

它在加载框架时第一次运行但是当我选择第二个项目时它给我错误

应用后 removeAllItems 然后组合框中没有项目

so getSelectedItem internally use the ComboBoxModel getSelectedItem 函数声明

The selected item or null if there is no selection

虽然 oracle docs 没有说明任何关于返回 null

解决方案:您在 null 中得到 nulltoString() 导致您出现空指针异常,因此请确保在调用 getSelectedItem 或放置空指针时有一些项目检查

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