简体   繁体   中英

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 duplication print of the 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());
 } 
}

I assume you have this code inside an itemStateChanged() method. the reason you get it twice is that it happens for both selecting the new value and de-selecting the old value.

Your code should look something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM