【问题标题】:two comboboxes related to each other [duplicate]两个相互关联的组合框[重复]
【发布时间】:2014-01-20 03:06:55
【问题描述】:

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

    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) 为了尽快获得更好的帮助,请发帖 SSCCE。将数据库分解出来,然后硬编码一些字符串来代替使用。 2) 源代码中的一个空白行总是就足够了。 { 之后或} 之前的空行通常也是多余的。 3)请不要忘记添加“?”提问!有些人在页面中搜索“?”如果“问题”中不存在,则直接转到下一个(实际)问题。
  • 您可以提供一个SSCCE ,您的查询似乎与这里无关,所以使用硬编码值。你需要addItemListener
  • 您似乎忽略了我的建议,因为您在我发表评论后回复了其他人。因此,我将简单地投票结束这种浪费我们时间的行为。
  • 我没有忽视你 :) 但我在这里得到了答案。非常感谢您的 cmets :)

标签: java swing jcombobox


【解决方案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();
         } 

}

【讨论】:

  • 每次更改时它都会不断添加酒店名称。我的意思是每次我更改城市时,都会将名称添加到 combobox2 .. 而不是更改它们。我该如何解决?
  • 我修好了,谢谢大家:)
  • 你介意设置我的anwser来更正吗?
  • 您的回答是正确的,但为了解决我在上一条评论中提到的问题,我添加了 jComboBox2.removeAllItems();到你的代码
  • 哦对了,我忘了!干杯伙伴。
猜你喜欢
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多