I have created a GUI and have a database located externally in which I fetch data from. I am using the GUI builder in NetBeans to do this. Does anyone know of a simple way to populate a jComboBox with values coming from the database? When I run the project there are no errors but the combo box remains empty.
Here is the code that sets the combo box with the names of discounts:
public void setDiscountNames(String type, JComboBox cbox) {
cbox.removeAllItems();
ArrayList<Discount> names = new ArrayList<Discount>();
try {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abpp034?user=abpp034&password=120001772");
stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = \"" + type + "\"");
rs = stmt.executeQuery();
while(rs.next()){
cbox.addItem(rs.getString("Name"));
}
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is located in a seperate class from the jComboBox object. This class is called Model.
Here is the place I call the setDiscountNames method in a form called DiscountGUIView:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){
model.setDiscountNames("Fixed", jComboBox1);
}
Okay (Update) the query does print the results:
run:
Travel Standard Fixed Standard BUILD SUCCESSFUL (total time: 1 second)
When trying to add elements dynamically to a combo box, use
MutableComboBoxModel.addElement
To remove all elements you could also do
Using the model methods will fire the necessary changes to update the ui
EDIT: This is your basic mistake.. you're calling the method in ActionPerformed !!
If the values are printing correctly then try this..
It might be that your
SELECT
query returns no results. To verify this, you can add logging statements inside thewhile (rs.next())
loop. My SQL knowledge is a bit rusty, but I remember using'
(single quotes) for string literals, whereas you use"
(double quotes) in your statement.Besides that, I see several things which could cause problems:
The SQL code for
PreparedStatement
should not be created by string concatenation. Instead, use?
for parameter values which will be substituted into the statement, e.g.It is strongly recommended that you explicitly close JDBC resources after being done with them. For this, you need to add a
finally
block after thecatch (SQLException ...)
, e.g.or, preferrably, use the
try-with-resources
statement (if you are using Java 7 and higher):