获取jcombobox所选项目

时间:2016-05-19 19:19:45

标签: java netbeans

我有这个代码,我想从jcombobox获取所选项目,但是当我运行我的项目时,它给我复制打印所选项目的值和java.Lang.NullPointerException 这是代码:

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

1 个答案:

答案 0 :(得分:3)

我假设您在itemStateChanged()方法中包含此代码。你得到它两次的原因是它既选择新值又取消选择旧值。

您的代码应该类似于:

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