【问题标题】:MySQL table values in JComboBoxJComboBox 中的 MySQL 表值
【发布时间】:2014-11-25 07:01:07
【问题描述】:

我设计了一个带有 MySQL 表的 swing 接口。 I put two comboboxes in a manner when the 1st combobox value is selected (Brand Name), the second combobox values (available items under thise selected brand) will be loaded via a mysql query.我的代码是...

try{
    String url = "jdbc:mysql://localhost:3306/databasename";
    String login = "root"; String password = ""; Connection con = DriverManager.getConnection(url, login, password);
    try{
        comboBox1 = new JComboBox(); comboBox1.setEditable(false);
        comboBox1.addItem("- - -");
        Statement stmt1=null;
        String query1 = "SELECT brand FROM brands";
        stmt1 = con.createStatement();
        ResultSet rs1 = stmt1.executeQuery(query1);
        while(rs1.next()) {comboBox1.addItem(rs1.getString(1));}
        comboBox2 = new JComboBox(); comboBox2.setEditable(false);
        comboBox1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event){
                String comboBox1Selected=comboBox1.getSelectedItem().toString();
                try{
                    Statement stmt2=null;
                    String query2 = "SELECT item FROM "+comboBox1Selected+"";
                    stmt2 = con.createStatement();
                    ResultSet rs2 = stmt2.executeQuery(query2);
                    while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}
                }
                catch (SQLException ex1) {JOptionPane.showMessageDialog(null,"Failed to Item-List..!"); ex1.printStackTrace(); return;}
            }
         });
    }
    catch (SQLException ex2) {JOptionPane.showMessageDialog(null,"Failed to Brand-List..!"); ex2.printStackTrace(); return;}
}
catch (SQLException ex3) {ex3.printStackTrace(); JOptionPane.showMessageDialog(null,"Unable to Connect..!"); return;}

问题是,即使组合框功能正常,如果我从第一个组合框中选择另一个选项,第二个组合框不会避免“旧值”(它们与新值一起出现)。

可能是什么原因..?任何人都可以解释..? 提前致谢。

【问题讨论】:

    标签: java jdbc jcombobox


    【解决方案1】:

    在此处添加新项目之前,请致电comboBox2.removeAllItems()while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-15
      • 2012-01-06
      • 2012-03-27
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多