[英]How to fetch selected item of JComboBox data into Swing text fields?
I have a table in my H2 database. 我的H2数据库中有一个表。
item_name | sac_hsn | price | Tax
And I have JTextfield
fields for hsn_code
and price
. 我有hsn_code
和price
JTextfield
字段。
Now what I want to do is when I select item_name
from JComboBox
then data of hsn_code
and price
of that item should also be fetch in the text fields. 现在我要做的是,当我从JComboBox
选择item_name
时,还应该在文本字段中获取hsn_code
数据和该商品的price
。
I have done this, but it's not working:- 我已经做到了,但是没有用:
When I run the code then in combo box it doesn't show any item. 当我运行代码时,在组合框中没有显示任何项目。 It was blank. 这是空白。
Connection connection = null;
ResultSet rs;
public void commonMethodForSt(String query) {
try {
Statement st = connection.createStatement();
rs = st.executeQuery(query);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
Then.. 然后..
public void populateItemNameAndDetails() {
try {
Class.forName("org.h2.Driver");
con =
DriverManager.getConnection("jdbc:h2:C:/SimpleGST/GST","sa","");
String pname = itemcombo.getSelectedItem().toString();
commonMethodForSt("select * from additems where item_name='"+pname+"'");
if(rs.next()) {
// System.out.print(set_com);
sachsntext.setText(rs.getString("sac_hsn"));
pricetext.setText(rs.getString("price"));
taxtext.setText(rs.getString("TAX_RATE"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After that I set an ActionListener
in the combo box and called the method in it. 之后,我在组合框中设置了一个ActionListener
在其中调用了方法。
itemcombo = new JComboBox();
itemcombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
populateItemNameAndDetails();
}
});
Okay, I solved that by creating a method that only populates data into comboBox. 好的,我通过创建一种仅将数据填充到comboBox中的方法解决了这一问题。
public void populateItemCombo() {
con = DriverManager.getConnection("jdbc:h2:C:/SimpleGST/GST", "sa", "");
itemcombo.addItem(" ");
commonMethodForSt("select * from additems");
while (rs.next()) {
itemcombo.addItem(rs.getString("item_name"));
}
}
and call the method. 并调用该方法。
and the codes that i asked as question are remain same. 和我作为问题询问的代码保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.