我有一个JCombobox,它从MySql表的列中获取数据。
public void FillCombo1(){
try {
String sql = "SELECT `Expense Code` FROM `database`.`expense_code_master`";
PreparedStatement pst = (PreparedStatement)conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("Expense Code");
comboBox.addItem(name);
}
}catch (Exception ex) {
System.out.println("Error: "+ex);
}
}
现在我想从同一个表中获取一个值,该值与我在组合框中选择的值相关。我怎么能这样做?
Table schema:
Expense Code (primary key) | Account No (int)
E120 | 12222
所以我想获取值(帐户编号)并将其与ActionListener放在JLabel中
答案 0 :(得分:0)
您可以利用ItemListener
来完成此任务。
JLabel myLabel = ... // Example JLabel from other part of program
...
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event){ // Fired on selection
if(event.getStateChange() == ItemEvent.SELECTED){ // Check for selection
Object item = event.getItem(); // Here is selected item
String expenseCode = item.toString(); // Get String
String result = ...; // Use query here -
// same way as with your other query
myLabel.setText(result); // Update JLabel with found String
}
}
}
请务必将ItemChangeListener
添加到JComboBox
。
comboBox.addItemListener(new ItemChangeListener());
SQL
查询将是这样的。
// expenseCode would be the String you got in the itemStateChanged method
String sql2 = "SELECT `Account No` FROM `database`.`expense_code_master` " +
"WHERE `Expense Code` == `" + expenseCode + "`";