Getting jcombobox selected item

I have this code and I want to get the selected item from jcombobox, but when I run my project, it gives me a copy of the duplicate value of the selected item and java.Lang.NullPointerException Here is the code:

 private void jComboBox4ItemStateChanged(java.awt.event.ItemEvent evt) {                                            
        // TODO add your handling code here:
         if (evt.getStateChange()==ItemEvent.SELECTED){

             String a=String.valueOf(jComboBox4.getSelectedItem());
         System.out.print(a);

         try{
        String del2="select distinct PTYPE from Projects inner join project on projects.PNUMBER=(select pro_id from project where pro_name='"+a+"')";
         psst=con.prepareStatement(del2);
        String td2;
          DefaultComboBoxModel mode2 = new DefaultComboBoxModel();
           ResultSet rss=psst.executeQuery();
           while(rss.next()){
            td2=rss.getString("PTYPE");
    mode2.addElement(td2);
       jComboBox7.setModel(mode2);
           }
    }
        catch(SQLException ex){
            JOptionPane.showMessageDialog(null, ex.toString());
 } 
}
+4
source share
1 answer

I assume you have this code inside a method itemStateChanged(). the reason you get it twice is because it happens to select a new value and deselect the old value.

Your code should look something like this:

    myCombo.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED) {
                String a=jcombobox.getselecteditem().toString();
                System.out.print(a); 
            }
        }
    });
+2
source

All Articles