自动提供组合框从mysql数据库中检索值

时间:2012-01-21 04:01:47

标签: java swing combobox jcombobox

使用以下java程序进行自动提取组合框检索mysql数据库中的值。自动建议正常工作。如果在组合框中键入“A”,则列表将显示以“A”开头的所有名称。在该表单中添加标签。如果我在组合框中选择一个名称,则表示相应的ID将显示在标签中。我的问题是我有四个名字在我的Sql数据库表中以'A'开头,如果我选择'A'起始名称将显示正确的Id.but我清除组合框文本列并输入'B'表示它显示所有名称都以'B'开头,但我单击“B”开始名称,它无法显示正确的ID,它显示'A'起始名称的ID。因为我使用getSelectedIndex()获取Id。如何获取自动建议组合框中所有名称的正确ID?

package combo;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;


public class comboauto extends javax.swing.JFrame {
         Vector  v=new Vector();
         Vector v1=new Vector();
         Statement TmpSqlStmnt;
         ResultSet TmpSqlRs;
         Connection con;
         int CateId;
         JTextField Txt01;

    public comboauto() {
        initComponents();
    }
   public void AutoSuggest() {
               Txt01=(JTextField)Cbx01.getEditor().getEditorComponent();
               Txt01.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e)
                {
                 EventQueue.invokeLater(new Runnable()
                 {
                   public void run() {
                   String text =Txt01.getText().toUpperCase();
                   if(text.length()==0)
                             {
                                Cbx01.hidePopup();
                                setModel(new DefaultComboBoxModel(v1), "");
                             }
                             else{
                                DefaultComboBoxModel m = getSuggestedModel(v1, text);
                               if(m.getSize()==0 ) {
                               Cbx01.hidePopup();
                                 }
                                else{
                                          setModel(m, text);
                                         Cbx01.showPopup();
                                     }
                                 }
                             }
                          });

                    }
                public void keyPressed(KeyEvent e)
                 {
                    String text = Txt01.getText();
                    int code = e.getKeyCode();
                    if(code==KeyEvent.VK_ENTER) {
                    if(!v1.contains(text)) {
                    v1.addElement(text);
                   // setModel(getSuggestedModel(v1, text), text);
            }
                    hide_flag = true;
        }else if(code==KeyEvent.VK_ESCAPE) {
         hide_flag = true;
        }else if(code==KeyEvent.VK_RIGHT) {
            for(int i=0;i<v1.size();i++) {
                String str = (String) v1.elementAt(i);
                if(str.startsWith(text))
                {
       //            Cbx01.setSelectedIndex(-1);
                   Txt01.setText(str);
                   return;
                }
            }
        }
            }
      });


      try{
        Class.forName("com.mysql.jdbc.Driver");
        con =DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");
        TmpSqlStmnt=con.createStatement();
        TmpSqlRs=TmpSqlStmnt.executeQuery ("SELECT CateId,CateName FROM Cust_Masterrecord ORDER BY CateName");
        System.out.println("DB Connected");
        Cbx01.removeAllItems();
        TmpSqlRs.first();
           if (Cbx01.getItemCount() == 0)
           {

               //Cbx01.addItem("");
             do
              {
               // String s= TmpSqlRs.getString("CateName");
                Cbx01.addItem(TmpSqlRs.getString("CateName"));
                CateId=TmpSqlRs.getInt("CateId");
                v.add(CateId);
                // s.valueOf(CateId);
                // System.out.println(s.valueOf(CateId));
                // System.out.println(CateId);
                // for(int i=0;i<CateName.length;i++){
                v1.addElement(TmpSqlRs.getString("CateName"));
                 //}
                  Cbx01.addItemListener(new ItemListener() {
                  public void itemStateChanged(ItemEvent e) {
                                     if (e.getStateChange() == ItemEvent.SELECTED) {

                                         //Cbx01.getItemCount();
                                         //System.out.println(Cbx01.getItemCount());
                                         //Cbx01.getSelectedItem();
                                         //System.out.println(Cbx01.getSelectedItem());

                                         Cbx01.getSelectedIndex();
                                        //System.out.println( Cbx01.getSelectedIndex());
                                        Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString());
                                      //System.out.println(v.get( Cbx01.getSelectedIndex()).toString());
                                    }
                                }
                            });

       }while(TmpSqlRs.next());
     }else{Cbx01.addItem("Records Not Available");}
   }catch(Exception e){
    System.out.println(e);
  }


    }

private boolean hide_flag = false;
       private void setModel(DefaultComboBoxModel mdl, String str) {
        Cbx01.setModel(mdl);
        //Cbx01.setSelectedIndex(-1);
        Txt01.setText(str);
    }
private static DefaultComboBoxModel getSuggestedModel(java.util.List<String> list, String text) {
        DefaultComboBoxModel m = new DefaultComboBoxModel();
        for(String s: list) {
            if(s.startsWith(text)) m.addElement(s);
        }
        return m;
    }




    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        Cbx01 = new javax.swing.JComboBox();
        Lbl01 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Cbx01.setEditable(true);
        Cbx01.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                Cbx01PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                Cbx01PopupMenuWillBecomeVisible(evt);
            }
        });
        Cbx01.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                Cbx01ComponentMoved(evt);
            }
        });
        Cbx01.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                Cbx01ItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(45, 45, 45)
                .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(103, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(110, 110, 110)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(170, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void Cbx01ItemStateChanged(java.awt.event.ItemEvent evt) {                                       
//Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString());        // TODO add your handling code here:
    }                                      

    private void Cbx01ComponentMoved(java.awt.event.ComponentEvent evt) {                                     
//Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString());        // TODO add your handling code here:
    }                                    

    private void Cbx01PopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {                                                 
    //   Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString()); // TODO add your handling code here:
    }                                                

    private void Cbx01PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {                                                   
      // Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString()); // TODO add your handling code here:
    }                                                  

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               comboauto Tmpobj1= new comboauto();
               Tmpobj1.AutoSuggest();
               Tmpobj1.setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox Cbx01;
    private javax.swing.JLabel Lbl01;
    // End of variables declaration                   

}

2 个答案:

答案 0 :(得分:0)

您可以将对象添加到组合框中,而不是添加字符串。该对象可以包含name和id,确保它具有返回名称的toString方法。然后,您可以通过在组合框上调用getSelectedItem来返回所选对象。

答案 1 :(得分:0)

do whilewhile(TmpSqlRs.next());)替换为while并检查输出是否正常......