How to fetch selected item of JComboBox data into Swing text fields?
How to fetch selected item of JComboBox data into Swing text fields?
I have a table in my H2 database.
item_name | sac_hsn | price | Tax
And I have JTextfield
fields for hsn_code
and price
.
JTextfield
hsn_code
price
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.
item_name
JComboBox
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();
);
BTW: change
} catch (Exception e) // TODO Auto-generated catch block
to } catch (Exception e) e.printStackTrace();
Or to put that another way: Don't ignore exceptions! They inform us exactly what went wrong. Unless logging is implemented, at least call Throwable.printStackTrace()
.– Andrew Thompson
Aug 22 at 8:28
} catch (Exception e) // TODO Auto-generated catch block
} catch (Exception e) e.printStackTrace();
Throwable.printStackTrace()
1 Answer
1
okay i solved that by first creating a method, that only populate data into 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.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example. Hard code some data to replace the DB.
– Andrew Thompson
Aug 22 at 8:24