Question

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)

Was it helpful?

Solution 3

EDIT: This is your basic mistake.. you're calling the method in ActionPerformed !!

classConstructor(){
setDiscountNames("Fixed", jComboBox1); // call this method here.. This will work.

}

If the values are printing correctly then try this..

List<String> strings = new ArrayList<String>();
while(rs.next()){

     strings.add(rs.getString("Name"));  // Confirm if "Name" is valid


    }
cbox.addItem(strings);

OTHER TIPS

It might be that your SELECT query returns no results. To verify this, you can add logging statements inside the while (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.

    stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?");
    stmt.setString(1, type); // first (and only) parameter
    rs = stmt.executeQuery();
    
  • 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 the catch (SQLException ...), e.g.

    } finally {
         try {
             if (rs != null) rs.close();
         } catch (SQLException ignore) {}
    
         try {
             if (stmt != null) stmt.close();
         } catch (SQLException ignore) {}
    
         try {
             if (conn != null) conn.close();
         } catch (SQLException ignore) {}
    }
    

    or, preferrably, use the try-with-resources statement (if you are using Java 7 and higher):

    try (Connection con = DriverManager.getConnection(...)) {
        // ...
        try (PreparedStatement stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?")) {
            // ...
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    // processing
                }
            }
        }
    } catch (SQLException) {
        Logger....;
    } // notice no finally block; resources are closed automatically
    

When trying to add elements dynamically to a combo box, use MutableComboBoxModel.addElement

JComboBox box = new JComboBox(new DefaultComboBoxModel());
....
MutableComboBoxModel model = (DefaultComboBoxModel)box.getModel();
while (rs.next()) {
    model.addElement(rs.getString("Name"));
}

To remove all elements you could also do

((DefaultComboBoxModel)box.getModel).removeAllElements();

Using the model methods will fire the necessary changes to update the ui

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top