自动建议组合框,可从 mysql 数据库检索值

发布于 2024-12-28 07:56:07 字数 9946 浏览 2 评论 0原文

我正在使用以下 java 程序作为自动建议组合框,从 mysql 数据库检索值。自动建议工作正常。如果我在组合框中键入“A”,则意味着列表将显示以“A”开头的所有名称。我添加标签如果我在组合框中选择一个名称,则意味着相应的 ID 将显示在标签中。我的问题是我的 Sql 数据库表中有四个以“A”开头的名称,如果我选择“A”开头的名称将显示正确的 ID。但是我清除了组合框文本列并输入“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                   

}

Am using the following java program for Autosuggestion combobox with retrieve the values from mysql database.the Auto Suggestion working properly.If i type 'A' in the combobox means the list will show the all names starting with 'A'.i add the label in that form.If i select the one name in combo box means the corresponding Id will display in the Label. My problem is i have the four names with starting 'A' in my Sql database table,if I select that 'A' starting name that will show correct Id.but I clear the combobox text column and type 'B' means it show the all name starting with 'B' but it I click the "B" started name it can't display the correct ID,It display the ID for 'A' starting name.because I get the Id using getSelectedIndex().how to get the correct ID for all names in auto suggest combobox?

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                   

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一杯敬自由 2025-01-04 07:56:07

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

You can add objects to the combo box instead of adding strings. The object can contain both name and id, make sure that it has toString method that returns the name. Then you can get back the selected object by calling getSelectedItem on the combo box.

橪书 2025-01-04 07:56:07

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

Replace do while (while(TmpSqlRs.next());) with while and check if output is coming properly or not...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文