How To Populate JTable Depending On JCombobox Selected Value In Java NetBeans
In this java Tutorial we will see How To Fill data Into JTable from Mysql database And Also Displaying Picture From Mysql Database In Java NetBeans .
Before: Insert Image In MySQL Database Using Java
Project Source Code:
// Step 1 Create A Class Named "Product2"
public class Product2 {
private String id;
private String name;
private int qte;
private String price;
private int catId;
private byte[] Image;
public Product2(){}
public Product2(String Id, String Name, int Qte, String Price,byte[] image, int CatId){
this.id = Id;
this.name = Name;
this.qte = Qte;
this.price = Price;
this.Image = image;
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;
}
public byte[] getMyImage(){
return Image;
}
}
// 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<Product2> BindTable(){
ArrayList<Product2> list = new ArrayList<Product2>();
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT `ID_PRO`, `PRO_NAME`, `QTE_IN_STOCK`, `PRICE`, `PRO_IMAGE`, `ID_CAT` FROM `products`");
Product2 p;
while(rs.next()){
p = new Product2(
rs.getString("ID_PRO"),
rs.getString("PRO_NAME"),
rs.getInt("QTE_IN_STOCK"),
rs.getString("PRICE"),
rs.getBytes("PRO_IMAGE"),
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 Class Named "TheModel"
package javaapp;
import javax.swing.Icon;
import javax.swing.table.AbstractTableModel;
public class TheModel extends AbstractTableModel {
private String[] columns;
private Object[][] rows;
public TheModel(){}
public TheModel(Object[][] data, String[] columnName){
this.rows = data;
this.columns = columnName;
}
public Class getColumnClass(int column){
// 4 is the index of the column image
if(column == 4){
return Icon.class;
}
else{
return getValueAt(0,column).getClass();
}
}
public int getRowCount() {
return this.rows.length;
}
public int getColumnCount() {
return this.columns.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return this.rows[rowIndex][columnIndex];
}
public String getColumnName(int col){
return this.columns[col];
}
}
ArrayList<Product2> list = new ArrayList<Product2>();
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT `ID_PRO`, `PRO_NAME`, `QTE_IN_STOCK`, `PRICE`, `PRO_IMAGE`, `ID_CAT` FROM `products`");
Product2 p;
while(rs.next()){
p = new Product2(
rs.getString("ID_PRO"),
rs.getString("PRO_NAME"),
rs.getInt("QTE_IN_STOCK"),
rs.getString("PRICE"),
rs.getBytes("PRO_IMAGE"),
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 Class Named "TheModel"
package javaapp;
import javax.swing.Icon;
import javax.swing.table.AbstractTableModel;
/**
*
* @author 1bestcsharp.blogspot.com
*/
public class TheModel extends AbstractTableModel {
private String[] columns;
private Object[][] rows;
public TheModel(){}
public TheModel(Object[][] data, String[] columnName){
this.rows = data;
this.columns = columnName;
}
public Class getColumnClass(int column){
// 4 is the index of the column image
if(column == 4){
return Icon.class;
}
else{
return getValueAt(0,column).getClass();
}
}
public int getRowCount() {
return this.rows.length;
}
public int getColumnCount() {
return this.columns.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return this.rows[rowIndex][columnIndex];
}
public String getColumnName(int col){
return this.columns[col];
}
}
// Step 4 Create A JFrame Named "JTableWithImage"
package javaapp;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.ImageIcon;
/**
*
* @author 1bestcsharp.blogspot.com
*/
public class JTableWithImage extends javax.swing.JFrame {
public JTableWithImage() {
initComponents();
populateJTable();
}
// create a methode to populate data Into JTable from Mysql database And Displaying Picture
public void populateJTable(){
MyQuery mq = new MyQuery();
ArrayList<Product2> list = mq.BindTable();
String[] columnName = {"Id","Name","Qte","Price","Image","Categorie"};
Object[][] rows = new Object[list.size()][6];
for(int i = 0; i < list.size(); i++){
rows[i][0] = list.get(i).getID();
rows[i][1] = list.get(i).getName();
rows[i][2] = list.get(i).getQte();
rows[i][3] = list.get(i).getPrice();
if(list.get(i).getMyImage() != null){
ImageIcon image = new ImageIcon(new ImageIcon(list.get(i).getMyImage()).getImage()
.getScaledInstance(150, 120, Image.SCALE_SMOOTH) );
rows[i][4] = image;
}
else{
rows[i][4] = null;
}
rows[i][5] = list.get(i).getCatID();
}
TheModel model = new TheModel(rows, columnName);
jTable1.setModel(model);
jTable1.setRowHeight(120);
jTable1.getColumnModel().getColumn(4).setPreferredWidth(150);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
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()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(248, 248, 248)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(261, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
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(JTableWithImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JTableWithImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JTableWithImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JTableWithImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JTableWithImage().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
///////////////OUTPUT:
Download Projects Source Code
2 comments
commentsdo you have the step by step procedure of retrieving blog data image from mysql to java where the code is written only in one java file?
ReplyHi, thank you for the helpful video
ReplyI'm using an access database and I'm struggling with the index of my image column. Your assistance would be highly appreciated