我正在寻找如何在第一个组合框上执行ActionPerformed以过滤下一个组合框。这是基于Mysql。 我正在使用以下代码填充第一个组合,这是正常工作
Vector<String> comboBoxItems = new Vector<String>();
final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(comboBoxItems);
try {
new MconnectionDB();
} catch (SQLException e2) {
e2.printStackTrace();
}
PreparedStatement st1 = null;
ResultSet rs1=null;
String strPro = "";
String sql1 ="select distinct T_AdressePro from t_adresse order by T_AdressePro";
try {
st1= MconnectionDB.con.prepareStatement(sql1);
rs1 = st1.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs1.next()){
strPro =rs1.getString("T_AdressePro");
comboBoxItems.add(strPro);
comboBoxPro= new JComboBox<String>(model);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
rs1.close();
st1.close();
new MdeconnectionDB();
}
catch (SQLException e) {
e.printStackTrace();
}
}
然后,我在第一个组合的ActionPerformed中添加了另一个类似的代码来过滤第二个组合:
comboBoxPro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Vector<String> comboBoxItemsC = new Vector<String>();
final DefaultComboBoxModel<String> modelC = new DefaultComboBoxModel<String>(comboBoxItemsC);
String strCir = "";
PreparedStatement st2 = null;
ResultSet rs2=null;
String sql2 ="select distinct T_AdresseCir from t_adresse where T_AdressePro=? order by T_AdresseCir";
try {
new MconnectionDB();
} catch (SQLException e2) {
e2.printStackTrace();
}
comboBoxPro.getSelectedItem();
strProCombo = comboBoxPro.getSelectedItem().toString();
System.out.println(strProCombo);
try {
st2= MconnectionDB.con.prepareStatement(sql2);
st2.setString(1, strProCombo); //strProCombo
rs2 = st2.executeQuery();
}catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs2.next()){
System.out.println(rs2.getString("T_AdresseCir"));
strCir =rs2.getString("T_AdresseCir");
comboBoxItemsC.add(strCir);
comboBoxCir= new JComboBox<String>(modelC);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
rs2.close();
st2.close();
new MdeconnectionDB();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
});
我注意到follogwing代码“System.out.println(rs2.getString(”T_AdresseCir“));”返回预期的结果,但不是组合框。还是空的。请帮助,谢谢。
答案 0 :(得分:0)
在您的actionPerformed
方法中,您正在创建新的JComboBox,但是您没有将其添加到gui。这可能是你无法看到其内容的原因。您应该创建新的ComboBoxModel并将其设置在现有的JComboBox上。您也应该使用STATICFILE_DIRS
来使代码更具可读性。
伪代码(我没有你的数据库):
// create new model for your comboBox
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
// fill model with data
try (Connection con = /*get connection to your db by any means necessary*/;
PreparedStatement stmt = con.prepareStatement(/*your query*/);
ResultSet rs = stmt.executeQuery();) {
while (rs.next()) {
model.addElement(rs.getString(/*your column*/));
}
comboBox.setModel(model); // set model for your JComboBox
} /*catch and all that*/
// no need for finally because try-with-resources.