How To Populate JCombobox Depending In Another JCombobox In Java NetBeans
In this java Tutorial we will see How To Fill data Into JCombobox from Mysql database
Depending On A JCombobox Value In Java NetBeans .
Project Source Code:
// Step 1 Create A Class Named "Product"
public class Product {
private String id;
private String name;
private int qte;
private String price;
private int catId;
public Product(){}
public Product(String Id, String Name, int Qte, String Price, int CatId){
this.id = Id;
this.name = Name;
this.qte = Qte;
this.price = Price;
this.catId = CatId;
}
public String getID(){
return id;
}
public void setID(String ID){
this.id = ID;
}
public String getName(){
return name;
}
public void setName(String Name){
this.name = Name;
}
public int getQte(){
return qte;
}
public void setQte(int Qte){
this.qte = Qte;
}
public String getPrice(){
return price;
}
public void setPrice(String Price){
this.price = Price;
}
public int getCatID(){
return catId;
}
public void setCatID(int CatID){
this.catId = CatID;
}
}
// 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.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author 1bestcsharp.blogspot.com
*/
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 ArrayList<Product> getData(int catID){
ArrayList<Product> list = new ArrayList<Product>();
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT `ID_PRO`, `PRO_NAME`, `QTE_IN_STOCK`, `PRICE`, `ID_CAT` FROM `products` WHERE `ID_CAT` = "+ catID);
Product p;
while(rs.next()){
p = new Product(
rs.getString("ID_PRO"),
rs.getString("PRO_NAME"),
rs.getInt("QTE_IN_STOCK"),
rs.getString("PRICE"),
rs.getInt("ID_CAT")
);
list.add(p);
}
} catch (SQLException ex) {
Logger.getLogger(MyQuery.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
// Step 3 Create A JFrame Named "JComboTutorial"
package javaapp;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JComboTutorial extends javax.swing.JFrame {
public JComboTutorial() {
initComponents();
BindCombo();
}
public void BindCombo(){
MyQuery mq = new MyQuery();
Connection con = mq.getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT `CAT_ID`, `CAT_NAME` FROM `categories`");
while(rs.next()){
combo1.addItem(rs.getInt(1));
}
} catch (SQLException ex) {
Logger.getLogger(JComboTutorial.class.getName()).log(Level.SEVERE, null, ex);
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
combo1 = new javax.swing.JComboBox();
combo2 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLocationByPlatform(true);
combo1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
combo1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 200, Short.MAX_VALUE)
.addComponent(combo2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(74, 74, 74))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(combo2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(176, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void combo1ActionPerformed(java.awt.event.ActionEvent evt) {
combo2.removeAllItems();
MyQuery mq = new MyQuery();
ArrayList<Product> list = mq.getData((int)combo1.getSelectedItem());
for(int i = 0; i < list.size(); i++){
combo2.addItem(list.get(i).getName());
}
}
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(JComboTutorial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JComboTutorial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JComboTutorial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JComboTutorial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JComboTutorial().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox combo1;
private javax.swing.JComboBox combo2;
// End of variables declaration
}
4 comments
commentsI have error to this:
Replywhile(rs.next()){
combo1.addItem(rs.getInt(1));
}
The error: Incompatible types: int caanot be converted to String
me error too
ReplyI have the same error... How can this be fixed?
ReplyDid somebody find an answer to this?
I can change the (rs.getInt(1)); to (rs.getString(1)); but that just gives me the name of the Column in the database... please help.
combo1.addItem(rs.getInt(1));
Hey guys,
ReplyI found a way to make the combobox accept an int.
Just go into the Combobox properties ---> Code ---->
And in the Type Parameters you probably have just like I did.
Just delete that text and it should work!