有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java两个相互关联的组合框

我有两个组合框。。。第一个显示酒店所在城市,第二个显示基于在第一个组合框中选择的城市的酒店名称。第一个组合框工作正常。第二个显示仅适用于第一个选定城市。在第一个组合框中更改城市后,它不会对自身进行更改!为了能够通过更改第一个组合框来查看第二个组合框中的更改,我必须向代码中添加什么内容

    try
    {

        Class.forName("com.mysql.jdbc.Driver");

        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
        Statement stat = con.createStatement();

        String City_Selected = jComboBox1.getSelectedItem().toString();           
        String select_HN = "select name from tbl_Hotel where city = '"+City_Selected+"';";

        ResultSet rs = stat.executeQuery(select_HN);



        while (rs.next())
        {              
            String hotel_name = rs.getString("name");
           // jLabel3.setText(hotel_name);
            jComboBox2.addItem(hotel_name);

         }//end while

        rs.close();
        stat.close();
        con.close();

         } catch (Exception e) {
              e.printStackTrace();
         } 

共 (1) 个答案

  1. # 1 楼答案

    像这样

    jComboBox1.addActionListener (new ActionListener () {
        public void actionPerformed(ActionEvent e) {
            jComboBox2.removeAllItems();
            fillComboBoxes();
        }
    });
    
    private void fillComboBoxes(){
    
     try
        {
    
            Class.forName("com.mysql.jdbc.Driver");
    
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
            Statement stat = con.createStatement();
    
            String City_Selected = jComboBox1.getSelectedItem().toString();           
            String select_HN = "select name from tbl_Hotel where city = '"+City_Selected+"';";
    
            ResultSet rs = stat.executeQuery(select_HN);
    
    
    
            while (rs.next())
            {              
                String hotel_name = rs.getString("name");
               // jLabel3.setText(hotel_name);
                jComboBox2.addItem(hotel_name);
    
             }//end while
    
            rs.close();
            stat.close();
            con.close();
    
             } catch (Exception e) {
                  e.printStackTrace();
             } 
    
    }