Java - How To Create Login Form In Java With MySQL Database

Java - How To Create Login Window In Java With MySQL Database In Java NetBeans

________________________________________________________

In this java Tutorial we will see Make A Login Form Using Java NetBeans And MySQL Database.

 
Part 1 


Part 2

Project Source Code:

// Create A JFrame Named "Java_Form_Login"

package javaapp;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;


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

    /**
     * Creates new form Java_Form_Login
     */
    public Java_Form_Login() {
        initComponents();
    }
    
// Set Timer
    Timer timer1 = new Timer(30, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
        
            if(jPanel_Message.getHeight() != 105){
                jPanel_Message.setBounds(0,0,Java_Form_Login.this.getSize().width,jPanel_Message.getHeight() + 5);
                if(jPanel_Message.getHeight() == 105){
                    timer1.stop();
                }
            }
        }
    });
    
        Timer timer2 = new Timer(30, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
        
            if(jPanel_Message.getHeight() != 0){
                jPanel_Message.setBounds(0,0,Java_Form_Login.this.getSize().width,jPanel_Message.getHeight() - 5);
                if(jPanel_Message.getHeight() == 0){
                    timer2.stop();
                }
            }
        }
    });
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField_Username = new javax.swing.JTextField();
        jPasswordField_Password = new javax.swing.JPasswordField();
        jCheckBox1 = new javax.swing.JCheckBox();
        jButton_Login = new javax.swing.JButton();
        jPanel_Message = new javax.swing.JPanel();
        jLabel_Message = new javax.swing.JLabel();
        jButton_Ok = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(java.awt.Color.decode("#bdb76b")
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Username :");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Password :");

        jTextField_Username.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jCheckBox1.setText("Show Password");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jButton_Login.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jButton_Login.setText("Login");
        jButton_Login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_LoginActionPerformed(evt);
            }
        });

        jPanel_Message.setBackground(java.awt.Color.decode("#3a5795"));

        jLabel_Message.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N

        jButton_Ok.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton_Ok.setText("Ok");
        jButton_Ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_OkActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel_MessageLayout = new javax.swing.GroupLayout(jPanel_Message);
        jPanel_Message.setLayout(jPanel_MessageLayout);
        jPanel_MessageLayout.setHorizontalGroup(
            jPanel_MessageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_MessageLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel_Message, javax.swing.GroupLayout.PREFERRED_SIZE, 483, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton_Ok, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50))
        );
        jPanel_MessageLayout.setVerticalGroup(
            jPanel_MessageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_MessageLayout.createSequentialGroup()
                .addGroup(jPanel_MessageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel_MessageLayout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addComponent(jLabel_Message))
                    .addGroup(jPanel_MessageLayout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(jButton_Ok, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPasswordField_Password)))
                .addGap(26, 26, 26)
                .addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(119, 119, 119))
            .addComponent(jPanel_Message, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel_Message, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(150, 150, 150)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jButton_Login, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(50, 50, 50)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jPasswordField_Password, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCheckBox1))))
                .addContainerGap(110, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

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

// Button Login
    private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {                                              

        Connection connection;
        PreparedStatement ps;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            ps = connection.prepareStatement("SELECT `username`, `password` FROM `users` WHERE `username` = ? AND `password` = ?");
            ps.setString(1, jTextField_Username.getText());
            ps.setString(2, String.valueOf(jPasswordField_Password.getPassword()));
            ResultSet result = ps.executeQuery();
            if(result.next()){
                jLabel_Message.setText("Login Successesfully");
                jLabel_Message.setForeground(Color.GREEN);
                timer1.start();
            }
            else{
                jLabel_Message.setText("Invalide Username Or Password");
                jLabel_Message.setForeground(Color.RED);
                timer1.start();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Java_Form_Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                             

    private void jButton_OkActionPerformed(java.awt.event.ActionEvent evt) {                                           
    
        timer2.start();
    }                                          

// Show And Hide Password Using jCheckBox
    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

        if(jCheckBox1.isSelected()){
            jPasswordField_Password.setEchoChar((char)0);
        }else{
          jPasswordField_Password.setEchoChar('*');
        }
    }                                          

    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(Java_Form_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Java_Form_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Java_Form_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Java_Form_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Java_Form_Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton_Login;
    private javax.swing.JButton jButton_Ok;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel_Message;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel_Message;
    private javax.swing.JPasswordField jPasswordField_Password;
    private javax.swing.JTextField jTextField_Username;
    // End of variables declaration                   
}




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

java login window with mysql
Invalid Username Or Password


java login window with mysql database
Login Successfully


C# - How To Create Login Form In C# With MySQL Database

C# - How To Create Login Window In C# With MySQL Database

                                                                                                                                         

In This C# Tutorial We Will See How To Make A Login Form Using CSharp Programming Language And MySQL Database.

                                                      
                                                                      Part 1


Part 2

Source Code :

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Csharp_And_MySQL
{
    public partial class Login_Form_2 : Form
    {
        public Login_Form_2()
        {
            InitializeComponent();
        }

        MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='test';username=root;password=");

        MySqlDataAdapter adapter;

        DataTable table = new DataTable();

        private void BTN_Login_Click(object sender, EventArgs e)
        {
            adapter = new MySqlDataAdapter("SELECT `username`, `password` FROM `users` WHERE `username` = '" + textBox_username.Text + "' AND `password` = '" + textBox_password.Text + "'", connection);
            adapter.Fill(table);

            if(table.Rows.Count <= 0)
            {
                panel1.Height = 0;
                label_Message.ForeColor = Color.Red;
                label_Message.Text = "Username Or Password Are Invalid";
                timer1.Start();
            }
            else
            {
                panel1.Height = 0;
                label_Message.ForeColor = Color.Green;
                label_Message.Text = "Login Successfully";
                timer1.Start();
            }

            table.Clear();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if(panel1.Height != 100)
            {
                panel1.Height = panel1.Height + 5;
                if(panel1.Height == 100)
                {
                    timer1.Stop();
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (panel1.Height != 0)
            {
                panel1.Height = panel1.Height - 5;
                if (panel1.Height == 0)
                {
                    timer2.Stop();
                }
            }
        }

        private void BTN_OK_Click(object sender, EventArgs e)
        {
            timer2.Start();
        }

        private void checkBox_ShowPass_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox_ShowPass.Checked)
            {
                textBox_password.UseSystemPasswordChar = true;
            }
            else
            {
                textBox_password.UseSystemPasswordChar = false;
            }
        }
       
    }
}

=> OutPut :

c# login window
Login Failed

c# login window
 Login Successfully


C# - How To Hide And Show Password Using C#

C# - How To Hide And Display Password Text Using C#

                                                                                             

In This C# Tutorial We Will See How To  Show And Hide Password Text In TextBox  With A CheckBox Using CSharp Programming Language .


Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Csharp_And_MySQL
{
    public partial class Show_Hide_Password : Form
    {
        public Show_Hide_Password()
        {
            InitializeComponent();
        }

        private void checkBox_Show_Hide_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox_Show_Hide.Checked)
            {
                textBox_Password.UseSystemPasswordChar = true;
            }
            else
            {
                textBox_Password.UseSystemPasswordChar = false;
            }
        }
    }
}

C# And MySQL - Populate Combobox Depending On Another Combobox Selected Value

C# And MySQL - Bind Combobox Depending On Another Combobox Selected Value

                                                                                             

In This C# Tutorial We Will See How To  Fill Data Into A ComboBox
Based On A ComboBox Selected value In CSharp Programming Language .


Source Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Csharp_And_MySQL
{
    public partial class Csharp_MySQL_datagridview_depending_combobox_value : Form
    {
        MySqlConnection con = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog ='project';username=root;password=");
        MySqlCommand command;
        MySqlDataAdapter adapter;
        DataTable table;

        public Csharp_MySQL_datagridview_depending_combobox_value()
        {
            InitializeComponent();
        }

        private void Csharp_MySQL_datagridview_depending_combobox_value_Load(object sender, EventArgs e)
        {
            string query = "SELECT `CAT_ID`, `CAT_NAME` FROM `categories`";
            comboBox_Categories.DataSource = getData(query);
            comboBox_Categories.DisplayMember = "CAT_NAME";
            comboBox_Categories.ValueMember = "CAT_ID";

            comboBox_Categories_SelectedIndexChanged(null, null);
        }

        public DataTable getData(string query)
        {
            command = new MySqlCommand(query, con);
            adapter = new MySqlDataAdapter(command);
            table = new DataTable();
            adapter.Fill(table);
            return table;
        }

        private void comboBox_Categories_SelectedIndexChanged(object sender, EventArgs e)
        {
            int val;
            Int32.TryParse(comboBox_Categories.SelectedValue.ToString(), out val);
            string query = "SELECT `ID_PRO`, `PRO_NAME`, `QTE_IN_STOCK`, `PRICE`, `ID_CAT` FROM `products` WHERE `ID_CAT` = " + val;
            dataGridView_Products.DataSource = getData(query);
        }
    }
}

=> OUTPUT:

Populate Combobox Depending On Another Combobox In C#

C# And MySQL - How To Populate DataGridView Depending On A Combobox Selected value

C# - How To Fill Data Into DataGridView Depending On A Combobox Selected value

                                                                                             

In This C# Tutorial We Will See How To  Bind Data Into A DataGridView 
Based On A Combobox Selected value In CSharp Programming Language And MySQL Database .


Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Csharp_And_MySQL
{
    public partial class Csharp_MySQL_datagridview_depending_combobox_value : Form
    {
        MySqlConnection con = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog ='project';username=root;password=");
        MySqlCommand command;
        MySqlDataAdapter adapter;
        DataTable table;

        public Csharp_MySQL_datagridview_depending_combobox_value()
        {
            InitializeComponent();
        }

        private void Csharp_MySQL_datagridview_depending_combobox_value_Load(object sender, EventArgs e)
        {
            string query = "SELECT `CAT_ID`, `CAT_NAME` FROM `categories`";
            comboBox_Categories.DataSource = getData(query);
            comboBox_Categories.DisplayMember = "CAT_NAME";
            comboBox_Categories.ValueMember = "CAT_ID";

            comboBox_Categories_SelectedIndexChanged(null, null);
        }

        public DataTable getData(string query)
        {
            command = new MySqlCommand(query, con);
            adapter = new MySqlDataAdapter(command);
            table = new DataTable();
            adapter.Fill(table);
            return table;
        }

        private void comboBox_Categories_SelectedIndexChanged(object sender, EventArgs e)
        {
            int val;
            Int32.TryParse(comboBox_Categories.SelectedValue.ToString(), out val);
            string query = "SELECT `ID_PRO`, `PRO_NAME`, `QTE_IN_STOCK`, `PRICE`, `ID_CAT` FROM `products` WHERE `ID_CAT` = " + val;
            dataGridView_Products.DataSource = getData(query);
        }
    }
}



=> OUTPUT:

c# filter datagridview using combobox

Java - How To Display image from JTable to JLabel In Java NetBeans

How To Display Picture From JTable To JLabel 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: Display Picture From Mysql Database To JTable In Java





Project Source Code:




// 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();
    }

    
 // populate jtable from mysql database and displaying image
    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>                        

// show image from jtable to jlabel
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
      
        int i = jTable1.getSelectedRow();
        if(jTable1.getValueAt(i, 4) != null)
        {
        ImageIcon image1 = (ImageIcon)jTable1.getValueAt(i, 4);
        Image image2 = image1.getImage().getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight()
                 , Image.SCALE_SMOOTH);
        ImageIcon image3 = new ImageIcon(image2);
        jLabel1.setIcon(image3);
        }
        else{
            System.out.println("No Image");
        }
    }                                    

    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:


Show image from JTable to JLabel In Java
Show image from JTable to JLabel In Java

Java And MySQL - How To Display Image From Mysql Database To JTable In Java NetBeans

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"

package javaapp;

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;


/**
 *
 * @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:


Display Image From Database To JTable In Java
Display Image From Database To JTable In Java