Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting jcombobox selected item

Tags:

java

netbeans

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());
 } 
}
like image 898
user6309713 Avatar asked May 19 '16 19:05

user6309713


People also ask

How do you check what is selected in a JComboBox?

You can use JComboBox#getSelectedIndex , which will return -1 if nothing is selected or JComboBox#getSelectedItem which will return null if nothing is selected.

Which event gets generated when you select an item from a JComboBox?

Which event gets generated when you select an item from a JComboBox? Combo boxes also generate item events, which are fired when any of the items' selection state changes.

What gets the number of items in the JComboBox?

getItemCount() : returns the number of items in the list. getItemListeners(): returns an array of all the ItemListeners added to this JComboBox with addItemListener().

Which method is used to add items to JComboBox?

Creates a JComboBox with a default data model. The default data model is an empty list of objects. Use addItem to add items.


1 Answers

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); 
            }
        }
    });
like image 168
Nir Levy Avatar answered Oct 11 '22 23:10

Nir Levy