Sabtu, 20 Juni 2015

Java And MySQL - How To Populate JCombobox From MySQL With Key And Value

How To Populate JCombobox From MySQL With Key And Value

In this java Tutorial we will see How To Fill data Into JCombobox from Mysql  database
using HashMap In Java NetBeans .


*Java Courses Java Complete Course

                            Java Swing Course



Project Source Code:

// Step 1 Create A Class Named "comboItem"

package javaapp;

public class comboItem {
    
    private int CatId;
    private String CatName;
    
    public comboItem(int catId, String catName){
        this.CatId = catId;
        this.CatName = catName;
    }
    
    public int getCatId(){
        return CatId;
    }
    
    public void setCatId(int id){
        this.CatId = id;
    }
    
    public String getCatName(){
        return CatName;
    }
    
    public void setCatName(String catName){
        this.CatName = catName;
    }
}

// Step 2 Create A Class Named "MyQuery"


package javaapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;


public class MyQuery {
    
   public Connection getConnection(){
        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/project", "root","");
        } catch (SQLException ex) {
            Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }

   public HashMap<String, Integer> populateCombo(){
      HashMap<String, Integer> map = new HashMap<String, Integer>();
      Connection con = getConnection();
      Statement st;
      ResultSet rs;
      
       try {
           st = con.createStatement();
           rs = st.executeQuery("SELECT `CAT_ID`, `CAT_NAME` FROM `categories`");
           comboItem cmi;
           
           while(rs.next()){
               cmi = new comboItem(rs.getInt(1), rs.getString(2));
               map.put(cmi.getCatName(), cmi.getCatId());
           }
           
       } catch (SQLException ex) {
           Logger.getLogger(MyQuery.class.getName()).log(Level.SEVERE, null, ex);
       }
      
       return map;
   }
}

// Step 3 Create A JFrame Named "ComboWithKeyAndValue"

package javaapp;

import java.util.HashMap;

/**
 *
 * @author 1bestcsharp.blogspot.com
 */
public class ComboWithKeyAndValue extends javax.swing.JFrame {

    public ComboWithKeyAndValue() {
        initComponents();
        BindCombo();
    }

// create the methode to fill combobox with keys and values
    public void BindCombo(){
        MyQuery mq = new MyQuery();
        HashMap<String, Integer> map = mq.populateCombo();
        for(String s : map.keySet()){
            jComboBox1.addItem(s);
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("jLabel1");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(213, 213, 213))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(267, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
      
        MyQuery mq = new MyQuery();
        HashMap<String, Integer> map = mq.populateCombo();
        jLabel1.setText(map.get(jComboBox1.getSelectedItem().toString()).toString());
    }                                          

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ComboWithKeyAndValue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ComboWithKeyAndValue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ComboWithKeyAndValue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ComboWithKeyAndValue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ComboWithKeyAndValue().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}


///////////////OUTPUT:

JCombobox From MySQL With Key And Value
JCombobox From Database With Key And Value

Bagikan

Jangan lewatkan

Java And MySQL - How To Populate JCombobox From MySQL With Key And Value
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.