Search code examples
javasqlswingjdbcjcombobox

Linking JComboBox with SQL


I am writing a code to make a list in JComboBox using the data in the database. It's actually for a POS system, where i have to select an item from a list in the database..

Here is the code i have been trying: (i did take try it without the while(itemsList != null) .. but it didnt work either

private class ButtonHandlerSales implements ActionListener 
{ 
    public final String userName = "root";
    private final String password = "";
    private final String serverName = "localhost";
    private final int portNumber = 3306;
    private final String dbName = "alphapos";



    public void actionPerformed(ActionEvent action) 
    {   
        Connection conn = null;
        try 
        {
            conn = this.getConnection();
        } 
        catch (SQLException e1) 
        {
            e1.printStackTrace();
        }
        //System.out.println("Connected to database");

        while(itemsList != null)
        {
            String[] list= null;
            String command = "SELECT itemName FROM item";

            try 
            {
                list = viewTable(conn, command);
            }
            catch (SQLException e) 
            {
                e.printStackTrace();
            }

            itemList = new JComboBox(list);


        }


    }

    private String[] viewTable(Connection con, String command) throws SQLException 
    {
        String list[] = null;
        Statement stmt = null;

        try 
        {
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(command);

            int i=0;
            while (rs.next()) 
            {
                list[i] = rs.getString("itemName");
                i++;
            }

        } 

        catch (SQLException e ) 
        {
            e.printStackTrace();
        } 

        finally
        {
            if (stmt != 
            null) { stmt.close(); }
        }

        return list;

    }

    private Connection getConnection() throws SQLException 
    {
        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", this.userName);
        connectionProps.put("password", this.password);

        conn = DriverManager.getConnection("jdbc:mysql://"
                + this.serverName + ":" + this.portNumber + "/" + this.dbName,
                connectionProps);

        return conn;
    }

}//end of class

I'm not getting any errors.. the code compiles.. but im not getting any output (list is empty).. Am i doing something wrong here?

Any help is really appreciated... ( im not looking for straight up codes )


Solution

  • Problem 1

    In your viewTable method String list[] = null;. You never initialize it with a new String[..]. So you will new a NullPointerException. But it would be better to use an ArrayList, since you may not know exactly how many values will be returned

    private List<String> viewTable(Connection con, String command) {
        List<String> list = new ArrayList<>();
        ...
        while (rs.next()) {
            list.add(rs.getString("itemName"));
        }
        return list;
    }
    

    Problem 2

    You are creating the JComboBox in the ActionListener. So you can't add the combo before the action is performed. With combo boxes, it's preferred to work with it's model, rather then the component, when working with the data. JComboBox has a ComboBoxModel. We can use the concrete DefaultComboBoxModel. You can pass an array to its constructor. List, has the method toArray we can call to create an array from the List. Then just pass the array to the DefaultComboBoxModel constructor and call the combo box setModel

    List<String> list = null;
    String command = "SELECT itemName FROM item";
    
    try {
        list = viewTable(conn, command);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    
    ComboBoxModel model = new DefaultComboBoxModel(list.toArray());
    itemList.setModel(model);
    

    This way, you can initialize the combo box before the action is performed.


    Update

    If you want the combo box loaded on application start up, I don't see what the problem is. Just create a method in you class, using the code in the actionPerformed. Then just call that method, like in your main constructor or something. Maybe you could do something like below, where you have the method return a ComboBoxModel and you can use to set the model for the combo box

    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Properties;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.ComboBoxModel;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    
    public class Test {
    
        private final JComboBox itemList;
    
        public Test() throws SQLException {
            itemList = new JComboBox(viewTable(getConnection(), command));
            JButton button = new JButton("Populate");
            button.addActionListener(new ButtonHandler());
    
            JPanel panel = new JPanel(new GridLayout(0, 1));
            panel.add(itemList);
            panel.add(button);
    
            JOptionPane.showMessageDialog(null, panel);
        }
    
        private class ButtonHandler implements ActionListener {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    ComboBoxModel model = viewTable(getConnection(), command);
                    itemList.setModel(model);
                } catch (SQLException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    
        }
    
        public static void main(String[] args) throws SQLException {
            Test test = new Test();
        }
    
        private ComboBoxModel viewTable(Connection con, String command) throws SQLException {
            List<String> list = new ArrayList<>();
            try (Statement stmt = con.createStatement()) {
                ResultSet rs = stmt.executeQuery(command);
    
                while (rs.next()) {
                    list.add(rs.getString("itemName"));
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            return new DefaultComboBoxModel(list.toArray());
    
        }
    
        public final String userName = "root";
        private final String password = "";
        private final String serverName = "localhost";
        private final int portNumber = 3306;
        private final String dbName = "alphapos";
        private final String command = "select itemName from item";
    
        private Connection getConnection() throws SQLException {
            Connection conn = null;
            Properties connectionProps = new Properties();
            connectionProps.put("user", this.userName);
            connectionProps.put("password", this.password);
    
            conn = DriverManager.getConnection("jdbc:mysql://"
                    + this.serverName + ":" + this.portNumber + "/" + this.dbName,
                    connectionProps);
    
            return conn;
        }
    }