将数据库中的值检索到组合框中

发布于 2024-12-28 03:24:19 字数 7048 浏览 1 评论 0原文

我使用以下程序将值从我的 sql 数据库检索到组合框。如果我使用 ResultSet 从 mysql 数据库选择 JComboBox 中的第一项,它不会显示第一项名称的 id 值。如果我选择组合框中的第二项(结果集) 它显示第二个选定项目名称的 id 值。在我单击第一个项目后,它会在标签框中显示第一个项目 Id 值。我的问题是第一个项目名称未在标签框中显示 ID 值,这意味着我的第一个记录集值未显示 id 值?

 package javacmbx;

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


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


    public comboautosuggest() {
        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);
                 }
                    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))
                {
                   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 location,pincode FROM combovalue ORDER BY location");
        System.out.println("DB Connected");
        TmpSqlRs.first();

             do
              {
                String s= TmpSqlRs.getString("location");
                Cbx01.addItem(s);
                CateId=TmpSqlRs.getInt("pincode");
                v1.addElement(s);
                v.addElement(CateId);
                Map.put(s, CateId);
                Cbx01.addItemListener(new ItemListener()
                {
                  public void itemStateChanged(ItemEvent e) {
                                     if (e.getStateChange() == ItemEvent.SELECTED) {
                                     Lbl01.setText(Map.get(Cbx01.getSelectedItem()).toString());
                                     }
                                }

                            });
       }while(TmpSqlRs.next());

    }catch(Exception e){
    System.out.println(e);
  }
  }
private boolean hide_flag = false;
       private void setModel(DefaultComboBoxModel mdl, String str) {
        Cbx01.setModel(mdl);
        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.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                Cbx01KeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                Cbx01KeyTyped(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(57, 57, 57)
                .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50)
                .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(77, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(190, Short.MAX_VALUE))
        );

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

    private void Cbx01KeyPressed(java.awt.event.KeyEvent evt) {
        //Txt01=(JTextField)Cbx01.getEditor().getEditorComponent();
    }

    private void Cbx01KeyTyped(java.awt.event.KeyEvent evt) {
        // TODO add your handling code here:
    }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                comboautosuggest Tmpcas=new comboautosuggest();
                Tmpcas.AutoSuggest();
                Tmpcas.setVisible(true);
            }
        });
    }

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

}

Am use the following program for retrieve the value from my sql database to combobox.if i select first item in JComboBox from mysql database using ResultSet, it's not showing an id value of the first item name. if i selected second item in combobox(result set)
it's showing the id value of the second selected item name. After i will click on first Item it's showing a first item Id value in label box. my problem is first item name is not showing ID value in label box, that means my first recordset value is not showing an id value?

 package javacmbx;

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


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


    public comboautosuggest() {
        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);
                 }
                    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))
                {
                   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 location,pincode FROM combovalue ORDER BY location");
        System.out.println("DB Connected");
        TmpSqlRs.first();

             do
              {
                String s= TmpSqlRs.getString("location");
                Cbx01.addItem(s);
                CateId=TmpSqlRs.getInt("pincode");
                v1.addElement(s);
                v.addElement(CateId);
                Map.put(s, CateId);
                Cbx01.addItemListener(new ItemListener()
                {
                  public void itemStateChanged(ItemEvent e) {
                                     if (e.getStateChange() == ItemEvent.SELECTED) {
                                     Lbl01.setText(Map.get(Cbx01.getSelectedItem()).toString());
                                     }
                                }

                            });
       }while(TmpSqlRs.next());

    }catch(Exception e){
    System.out.println(e);
  }
  }
private boolean hide_flag = false;
       private void setModel(DefaultComboBoxModel mdl, String str) {
        Cbx01.setModel(mdl);
        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.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                Cbx01KeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                Cbx01KeyTyped(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(57, 57, 57)
                .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50)
                .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(77, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(190, Short.MAX_VALUE))
        );

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

    private void Cbx01KeyPressed(java.awt.event.KeyEvent evt) {
        //Txt01=(JTextField)Cbx01.getEditor().getEditorComponent();
    }

    private void Cbx01KeyTyped(java.awt.event.KeyEvent evt) {
        // TODO add your handling code here:
    }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                comboautosuggest Tmpcas=new comboautosuggest();
                Tmpcas.AutoSuggest();
                Tmpcas.setVisible(true);
            }
        });
    }

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

}

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

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

发布评论

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

评论(1

夏末的微笑 2025-01-04 03:24:19

当您从数据库加载记录时,您将在 while 循环中执行两件事:

  1. 将一个项目添加到 JComboBox 中。
  2. ItemListener 添加到 JComboBox

这有两个含义:首先,您要添加多个项目侦听器,即每个记录一个。每当您更改所选值时,所有这些都会被触发。由于它们都执行相同的操作,因此无需声明多个操作。将 Cbx01.addItemListener(new ItemListener() { ... }); 移到循环之外。

其次,在第一个项目本身之后添加项目侦听器。因此,添加第一个值根本无法触发侦听器,因此不会显示 id(如果您再次使用鼠标选择第一个项目,则会显示 id)。

我建议您将 addItemListener 移到循环之前。实例化 JComboBox 本身是一个好地方。

When you load the records from your database you are doing two things inside the while-loop:

  1. Add an item to the JComboBox.
  2. Add an ItemListener to the JComboBox.

This has two implications: first you are adding multiple item listeners, namely one for each record. Whenever you change the selected value all of them will be triggered. Since they all perform the same action it is not necessary to declare more than one. Move the Cbx01.addItemListener(new ItemListener() { ... }); outside the loop.

Second you add the item listener after the first item itself. Therefore, adding the first value cannot trigger the listener at all and thus no id is shown (it will be show if you again select the first item using the mouse).

I suggest you move the addItemListener before the loop. A good place would be where you instanciate the JComboBox itself.

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