JComboBox (javax.swing.JComboBox) Explained

UPDATED: 21 April 2013
I generally work around web application. I didn't have much idea about desktop application in Java. I got client wants to create Inventory Management application. I found that its little bit hard to deal with the JComboBox when work around dynamic data. Let me show you how you can hide some of data (i.e database ID, Description, etc...) related to selected item.


Step 1. How to load data in JComboBox when form open or load or called from other class?
Use the function  private void formWindowOpened(java.awt.event.WindowEvent evt). I'll give you code snippet that'll help you to understand in better way.
private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        Vector comboBoxItems = new Vector();
        boolean productCount = true;
        String itemID = "", name = "", manufacturer = "", stock = "";
        try {
            Connection con = variables.getDatabaseConnection();
            PreparedStatement product_stmt = con.prepareStatement("select * from warehouse");
            ResultSet product_rs = product_stmt.executeQuery();
            comboBoxItems.add(new Item(0, "Select Item"));
            while (product_rs.next()) {
                productCount = false;
                itemID = product_rs.getString("idwarehouse");
                name = product_rs.getString("NameOfProduct");
                // To understand below code please read the question 2 in this article
                comboBoxItems.add(new Item(Integer.parseInt(itemID), name));
            }
            if (productCount) {
                comboBoxItems.add(new Item(0, "No Item Available"));
            }
            con.close();
            final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
            jComboBox1.setModel(model);
            jComboBox1.addActionListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
}
Step 2. How to bind the data within JComboBox?
To bind the data for each item we use the below function. That'll also help us to retrieve the data when value of JComboBox is changed or say action performed.
class Item {
        private int id;
        private String description;

        public Item(int id, String description) {
            this.id = id;
            this.description = description;
        }

        public int getId() {
            return id;
        }

        public String getDescription() {
            return description;
        }

        public String toString() {
            return description;
        }
}
Step 3. How to handle event on JComboBox?
Implement the ActionListener for the current class (i.e java file, form, etc...). Modify the line public class name_of_file extends javax.swing.JFrame to public class productStock extends javax.swing.JFrame implements ActionListener. As you are Overriding the ActionListener you have to add that function like below.
@Override
public void actionPerformed(ActionEvent e){
//implement code
}

Now let me show you code snippet that demonstrate the action of change value in JComboBox.
@Override
public void actionPerformed(ActionEvent e) {
/*
* If you are performing action listener for other component then use below code
* if(e.getSource()==jComboBox1){
* Put the below code within IF box          
* }
*/
        jComboBox1 = (JComboBox) e.getSource();
        Item item = (Item) jComboBox1.getSelectedItem();
        //Implement your code here
        System.out.println("Database ID of selected value"+String.valueOf(item.getId()));
        try {
            Connection con = variables.getDatabaseConnection();
            PreparedStatement warehouse_stmt = con.prepareStatement("select * from warehouse where(idwarehouse=?) limit 0,1");
            warehouse_stmt.setString(1, String.valueOf(item.getId()));
            ResultSet warehouse_rs = warehouse_stmt.executeQuery();
            if (warehouse_rs.next()) {
                jTextField1.setText(warehouse_rs.getString("NameOfProduct"));
            } else {
                JOptionPane.showMessageDialog(rootPane, "Select proper item");
            }
            con.close();
        } catch (Exception exp) {
            JOptionPane.showMessageDialog(rootPane, exp.getMessage());
        }
}     
You have to add all this 3 code in your file in order to work.
  1. It'll load data when window opened (note: If you want it to load on other action use the code with in function. [i.e : On click, On focus, etc...]).
  2. It'll bind data in JComboBox.
  3. It'll handle the change event of JComboBox.

0 comments :