Search code examples
javaswingjdbcjcomboboxitemlistener

How do i get Combobox item count?


i have 2 combobox combobox1(fogcomb) is fill with movie title and i want to if i choose the 2nd item in fogcomb then int asd variable get 2 value and if i choose 4th item then value=4

fogcomb2.addItemListener(new ItemListener(){
        @Override
        public void itemStateChanged(ItemEvent e){
            asd=fogcomb.getSelectedIndex();

            if (e.getItem().equals(tesztvalt)) {
    try {
      String sql="SELECT Idő,Terem FROM Idopontok I,Filmlista F WHERE Cím like'"+tesztvalt+"'and I.FKód=F.FKód and I.FKód='"+asd+"'"; 
                PreparedStatement pst = conn.prepareStatement(sql);
                ResultSet rs = pst.executeQuery();

                    while (rs.next()) {
                        String name=rs.getString("Idő");
                        String name2=rs.getString("Terem");
                        String name3="   ";
                        fogcomb2.addItem(name+name3+name2);             
                    }

                        }catch(Exception ex) {
                            JOptionPane.showMessageDialog(null, e);

Solution

  • As the indexes are 0 based you should use :

    asd=fogcomb.getSelectedIndex() + 1;
    

    EDIT

    You are adding itemlistener to wrong combobox

    fogcomb2.addItemListener(new ItemListener(){
    

    should be replaced by:

    fogcomb.addItemListener(new ItemListener(){