0

私はスイングからjcomboboxを使用しており、getSelectedIndexメソッドから予期しない出力を取得しています。最初の JComboBox を選択すると、2 番目のコンボボックスが有効になり、getSelectedIndex() メソッドを使用すると予期しない出力が表示されます。つまり、「0」と表示されるはずですが、「0」、「-1」、例外、最後に「0」が表示されています。例外の原因がわかりません。ここではコードの一部のみを示していますが、皆さんが私を理解してくれることを願っています...

    public Tester() {
            super("Utility for publish_date");
            Container contentpane = getContentPane();
            contentpane.setLayout(new BorderLayout());

            try{
            conn = new MyConn().getMyConnection();
             s = conn.createStatement();
             rs = s.executeQuery("select distinct state_name , state_code from state_master where state_code in (select statecode from pdf_detail) order by state_name");
             statelist.add(0,"Select state");
             while(rs.next())
            {
                statelist.add(rs.getString(1));
                statecodelist.add(rs.getString(2));
            }

             System.out.println("the content of statelist"+ statelist);
           System.out.println("the content of statecodelist"+statecodelist);


             list_state  = new String [statelist.size()];
            statelist.toArray(list_state);


            }catch(Exception e)
            {
                System.out.println(e);
                log(e.getMessage());
            }


            combo = new JComboBox(list_state);
            combo.setBounds(50, 50, 100, 20);
            combo.addActionListener(this);


            combo1 = new JComboBox();
            combo1.addActionListener(this);
            combo1.setEnabled(true);

            combo1.setBounds(50, 100, 100, 20);

            combo2 = new JComboBox();
            combo2.addActionListener(this);
            combo2.setEnabled(true);

            combo2.setBounds(50, 100, 100, 20);

            JPanel panel1 = new JPanel(new FlowLayout());
            panel1.add(combo);
            panel1.add(combo1);
            panel1.add(combo2);
            contentpane.add(panel1 , BorderLayout.NORTH);


          label = new JLabel();
          label.setText("Choose publish Date by selecting below.");
          final SimpleDateFormat dateformater = new SimpleDateFormat("yyyy-MM-dd");

        datepicker = new JXDatePicker();
        datepicker.setFormats(dateformater);

        datepicker.addActionListener(new ActionListener(){

                  public void actionPerformed(ActionEvent e)  {
                       //label.setText(datepicker.getDate().toString());
                     System.out.println("new date is "+dateformater.format(datepicker.getDate()));
                    publish_date =    dateformater.format(datepicker.getDate());

                  }
        });



        JPanel panel2 = new JPanel(new FlowLayout());
        panel2.add(label);
        panel2.add(datepicker);
        contentpane.add(panel2 , BorderLayout.CENTER);




            pbutton = new JButton("Submit");
            pbutton.addActionListener(this);

           JPanel panel3 = new JPanel();
           panel3.add(pbutton);
           contentpane.add(panel3 , BorderLayout.SOUTH);


            setSize(600,150);

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }



    public void actionPerformed(ActionEvent a) 
    {
        if (a.getSource() == combo) {


            statename = (String)combo.getSelectedItem();
            System.out.println("statename======="+statename);
             q = combo.getSelectedIndex();
        System.out.println("....q....."+q);
            System.out.println(",,,,,,,,,,"+statecodelist.get(q-1));

            try{
                districtcodelist.clear();
                ResultSet rs2 =s.executeQuery("select distinct district_name , district_code from district_master where state_code= '"+statecodelist.get(q-1)+"' AND district_code in (select districtcode from pdf_detail where statecode =  '"+statecodelist.get(q-1)+"') order by district_name ");
                //districtlist.add(0, "Select district");
                while(rs2.next())
                {
                    districtlist.add(rs2.getString(1));
                    districtcodelist.add(rs2.getString(2));

                }

                 System.out.println("the content of districtlist"+ districtlist);
                 System.out.println("the content of districtcodelist"+districtcodelist);


                 list_district  = new String [districtlist.size()];
                 districtlist.toArray(list_district);
            }catch(Exception f)
            {
                 f.printStackTrace();
                 System.out.println(f);
                 log(f.getMessage());

            }
            //combo1.setEnabled(true);
            combo1.removeAllItems();
            for (int i = 0; i < list_district.length; i++) {
                     combo1.removeItem(list_district[i]);
                    combo1.addItem(list_district[i]);

            }
            districtlist.clear();
        }

        else if (a.getSource() == combo1)
        {
           // System.out.println("combo1");
            districtname = (String)combo1.getSelectedItem();
            System.out.println("districtname========"+districtname);
             w = combo1.getSelectedIndex();

             if(w == -1)
             {
                 System.out.println("hre is the prob");
                 System.out.println(combo1.getSelectedItem());
             }
            System.out.println(".....w...."+w);
            System.out.println(combo1.getSelectedItem());
            //System.out.println(",,,,,,,,,,"+districtcodelist.get(w));

            try{
                //tehsillist.add(0,"Select tehsil");


                ResultSet rs3 = s.executeQuery("select distinct tehsil_name , tehsil_code from tehsil_master where state_code= '"+statecodelist.get(q-1)+"' AND district_code='"+districtcodelist.get(w)+"' AND tehsil_code in ( select tehsilcode from pdf_detail where statecode =  '"+statecodelist.get(q-1)+"' AND districtcode = '"+districtcodelist.get(w)+"') order by tehsil_name");

                while(rs3.next())
                {
                    tehsillist.add(rs3.getString(1));
                }


                list_tehsil = new String [tehsillist.size()];
                tehsillist.toArray(list_tehsil);


            }catch(Exception g)
            {
             g.printStackTrace();
             log(g.getMessage());
            System.out.println(g);
        }
            //combo2.setEnabled(true);
            combo2.removeAllItems();
            for (int i = 0; i < list_tehsil.length; i++) {
                combo2.removeItem(list_tehsil[i]);
                combo2.addItem(list_tehsil[i]);
        }
            tehsillist.clear();
        }







        if(a.getSource() == pbutton){
             tehsilname = (String)combo2.getSelectedItem();
             e = combo2.getSelectedIndex();
             System.out.println("....e....."+e);
             System.out.println("....w....."+w);

               if((String)combo.getSelectedItem()== "Select state" || (String)combo1.getSelectedItem()== "Select district" || (String)combo2.getSelectedItem()== "Select tehsil" || publish_date == null  )
               {
                  JOptionPane.showMessageDialog(this, "Select all four items first.");
               }
               else 
               {
                 int c = JOptionPane.showConfirmDialog(this,"Do you really want to continue?","update publish date?",JOptionPane.YES_NO_OPTION);
                   if(c==0)
                   {
                   log("State is "+statename+"  \nDistrict is "+districtname+"  \nTehsil is "+tehsilname);
                  try{


              Properties pr =new Properties();
               pr.load(new FileInputStream("config/config.properties"));
              //String publish_date =  pr.getProperty("publish_date");

              ResultSet rs4 = s.executeQuery("select publish_date from pdf_detail where statecode = (select state_code from state_master where state_name = '"+statename+"') AND districtcode = (select district_code from district_master where district_name = '"+districtname+"') AND tehsilcode = (select tehsil_code from tehsil_master where tehsil_name = '"+tehsilname+"') ");

              while(rs4.next())
              {
                  testvalue = rs4.getString(1);

              }
              if(testvalue != null)
              {


                  n = JOptionPane.showConfirmDialog(this,"Publish_date is already assigned to this tehsil. Do you want to update it?","update publish date?",JOptionPane.YES_NO_OPTION);
                 System.out.println("the value of n is "+n);
              }

              if(testvalue == null ||  n == 0)
              {
                 JOptionPane.showMessageDialog(this, "Publish_date updated");  
                  s.executeUpdate("Update pdf_detail set publish_date = '"+publish_date+"'where statecode=(select state_code from state_master where state_name='"+statename+"') AND districtcode=(select district_code from district_master where district_name='"+districtname+"') AND tehsilcode=(select tehsil_code from tehsil_master where tehsil_name='"+tehsilname+"')");
                  log("publish date of "+tehsilname+" is updated from ("+testvalue+") to ("+publish_date+")");
              }
           }catch(Exception e){
               log(e.getMessage());
               System.out.println(e);}

           if(n==1)
           {
              JOptionPane.showMessageDialog(this, "Pulish_date updation canceled");
              log("publish_date process canceled as it is already done");
           }


          JOptionPane.showMessageDialog(this, "Proces completed");
          log("process completed at");
          log("------------------------------------------------------------------------");
         excelLog();


               }
                   else{
                       setVisible(false);
                     (new Publish_Date()).setVisible(true);

                   }

               }
               }    
    }











    public static void main(String args[]) {
             log("process start time");
            (new Tester()).setVisible(true);
    }

}

出力:

....q.....1

.....w....0

....q.....1

.....w....-1

java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.get(Unknown Source)
at com.Publish_Date.itemStateChanged(Publish_Date.java:215)
at javax.swing.JComboBox.fireItemStateChanged(Unknown Source)
at javax.swing.JComboBox.selectedItemChanged(Unknown Source)
at javax.swing.JComboBox.contentsChanged(Unknown Source)
at javax.swing.AbstractListModel.fireContentsChanged(Unknown Source)
at javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source)
at javax.swing.DefaultComboBoxModel.removeElementAt(Unknown Source)
at javax.swing.DefaultComboBoxModel.removeElement(Unknown Source)
at javax.swing.JComboBox.removeItem(Unknown Source)
at com.Publish_Date.itemStateChanged(Publish_Date.java:190)
at javax.swing.JComboBox.fireItemStateChanged(Unknown Source)
at javax.swing.JComboBox.selectedItemChanged(Unknown Source)
at javax.swing.JComboBox.contentsChanged(Unknown Source)
at javax.swing.AbstractListModel.fireContentsChanged(Unknown Source)
at javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
java.lang.ArrayIndexOutOfBoundsException: -1

.....w....0
4

2 に答える 2

1

項目が選択されていない場合、JComboBox の選択されたインデックスは -1 です。2 番目のチェックボックスのアイテムが選択されていて、最初のチェックボックスの選択を変更すると、2 番目のチェックボックスのすべてのアイテムが によって削除されますcombo1.removeAllItems();。これにより、チェックボックスの選択が -1 に変更され、イベントが発生します。

ほとんどの場合、-1 値を検出して、イベントを無視するか、クリーンアップを実行できます。

于 2012-07-12T08:16:54.897 に答える
0

ActionListenerを試す

JComboBox<String> jb =  new JComboBox<String>();

jb.add("Vivek"):
jb.add("Vicky");

jb.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {



        System.out.println(jb.getSelectedIndex());
    }
});
于 2012-07-12T06:29:04.257 に答える