我设计了一个带MySQL表的swing接口。当选择第一个组合框值(品牌名称)时,我以两种方式放置两个组合框,第二个组合框值(所选品牌下的可用项目)将通过mysql查询加载。我的代码是......
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;}
问题是,尽管组合框运行正常,但如果我从第一个组合框中选择另一个选项,则第二个组合框不会避免使用较旧的值" (它们以较新的值出现)。
可能是什么原因......?任何人都可以解释..? 提前谢谢。
答案 0 :(得分:2)
在此处comboBox2.removeAllItems()
while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}