Java And MySQL - Data And Images Navigation From MySQL Database Using NetBeans

Java Code -  Navigate And Display Images And Records From MySQL DataBase Using NetBeans .

                                                                           


In this java Tutorial we will see How To Create A Buttons Navigation To Display Data And Images From MySQL Database Using NetBeans .




Part 1


Part 2


Create A Class And Call It Item :

package JAVA_VIDEOS_TUTORIALS;

public class Item {
    
    private String id;
    private String name;
    private String description;
    private byte[] image;
    
    public Item(String ID, String NAME, String DESCRIPTION, byte[] IMAGE)
    {
        this.id = ID;
        this.name = NAME;
        this.description = DESCRIPTION;
        this.image = IMAGE;
    }
    
    public String getId()
    {
        return id;
    }
    
    public String getName()
    {
        return name;
    }
    
    public String getDescription()
    {
        return description;
    }
    
    public byte[] getImage()
    {
        return image;
    }
}


Methods :
    - Method "getConnection" This Method Return The Connection :
       
     public Connection getConnection()
    {
        Connection con = null;

        try{
            con = DriverManager.getConnection("jdbc:mysql://localhost/db_images", "root", "");
        }
      catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return con;
    }

 - Method "getItemsList" This Method Populate A list Of Item With Data From Mysql Database And Return This List :

 public List<Item> getItemsList()
    {
        try {
            Connection connection = getConnection();

            Statement st = connection.createStatement();

            ResultSet rs = st.executeQuery("SELECT * FROM myimages");

            List<Item> list = new ArrayList<Item>();

            Item item;

            while(rs.next())
            {
               item = new Item(rs.getString("ID"),rs.getString("Name"),
                      rs.getString("Description"),rs.getBytes("Image"));
               
               list.add(item);
            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 - Method "showItem" This Method Take One Parameter Which Is The Index Of The Item In The List Returned By The "getItemsListMethod And Show Records And Display Image With The Same Width And Height As The JLabel :
   
public void showItem(int index)
    {
        jTextField_id.setText(getItemsList().get(index).getId());

        jTextField_name.setText(getItemsList().get(index).getName());

        jTextArea_description.setText(getItemsList().get(index).getDescription());
        
        ImageIcon icon = new ImageIcon(getItemsList().get(index).getImage());

        Image image = icon.getImage().getScaledInstance(jLabel_image.getWidth(), 
                                 jLabel_image.getHeight(), Image.SCALE_SMOOTH);

        jLabel_image.setIcon(new ImageIcon(image));
    }

Project Source Code:
    
package JAVA_VIDEOS_TUTORIALS;

import java.awt.Image;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;

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

    /**
     * Creates new form java_images_and_data_database_navigation
     */
    public java_images_and_data_database_navigation() {
        initComponents();
     // display the first item
        showItem(pos);
    }

// the index of the items
    int pos = 0;
    
 // get the connection
    public Connection getConnection()
    {
        Connection con = null;
        try{
            con = DriverManager.getConnection("jdbc:mysql://localhost/db_images", "root", "");
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return con;
    }
    

 // bind a list of item from mysql database
    public List<Item> getItemsList()
    {
        try {
            Connection connection = getConnection();

            Statement st = connection.createStatement();

            ResultSet rs = st.executeQuery("SELECT * FROM myimages");

            List<Item> list = new ArrayList<Item>();

            Item item;

            while(rs.next())
            {
               item = new Item(rs.getString("ID"),rs.getString("Name"),
                      rs.getString("Description"),rs.getBytes("Image"));
               
               list.add(item);
            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
     // show records and image from database 
    public void showItem(int index)
    {
        jTextField_id.setText(getItemsList().get(index).getId());

        jTextField_name.setText(getItemsList().get(index).getName());

        jTextArea_description.setText(getItemsList().get(index).getDescription());
        
        ImageIcon icon = new ImageIcon(getItemsList().get(index).getImage());

        Image image = icon.getImage().getScaledInstance(jLabel_image.getWidth(), 
                                 jLabel_image.getHeight(), Image.SCALE_SMOOTH);

        jLabel_image.setIcon(new ImageIcon(image));
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel_image = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea_description = new javax.swing.JTextArea();
        jTextField_id = new javax.swing.JTextField();
        jTextField_name = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton_Next = new javax.swing.JButton();
        jButton_previous = new javax.swing.JButton();
        jButton_last = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(153, 51, 0));

        jLabel1.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Id :");

        jLabel2.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Name :");

        jLabel3.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Description :");

        jScrollPane1.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N

        jTextArea_description.setColumns(20);
        jTextArea_description.setRows(5);
        jScrollPane1.setViewportView(jTextArea_description);

        jTextField_id.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N

        jTextField_name.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/first.png"))); // NOI18N
        jButton1.setText("First");
        jButton1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButton1.setIconTextGap(0);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton_Next.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton_Next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/next.png"))); // NOI18N
        jButton_Next.setText("Next");
        jButton_Next.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButton_Next.setIconTextGap(0);
        jButton_Next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_NextActionPerformed(evt);
            }
        });

        jButton_previous.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton_previous.setIcon(new javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/previous.png"))); // NOI18N
        jButton_previous.setText("Previous");
        jButton_previous.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButton_previous.setIconTextGap(0);
        jButton_previous.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_previousActionPerformed(evt);
            }
        });

        jButton_last.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton_last.setIcon(new javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/last.png"))); // NOI18N
        jButton_last.setText("Last");
        jButton_last.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButton_last.setIconTextGap(0);
        jButton_last.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_lastActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel_image, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(jTextField_id)
                    .addComponent(jTextField_name, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46)
                .addComponent(jButton_Next, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(jButton_previous, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addComponent(jButton_last, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel_image, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField_id, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextField_name, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(73, 73, 73)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_Next, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_previous, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_last, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(52, 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();
    }// </editor-fold>                        

  
     // The First , Next , Previous ,Last Navigation Buttons
 // First
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      
        pos = 0;
        showItem(pos);
                
    }                                        
    
   // Next
    private void jButton_NextActionPerformed(java.awt.event.ActionEvent evt) {                                             
        pos++;
        if(pos >= getItemsList().size())
        {
            pos = getItemsList().size()-1;
        }
        showItem(pos);
    }                                            


// Previous
    private void jButton_previousActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        pos--;
        if(pos < 0)
        {
            pos = 0;
        }
        showItem(pos);
    }                                                

// Last
    private void jButton_lastActionPerformed(java.awt.event.ActionEvent evt) {                                             
        
        pos = getItemsList().size() - 1;
        showItem(pos);
        
    }                                            

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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_images_and_data_database_navigation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(java_images_and_data_database_navigation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(java_images_and_data_database_navigation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(java_images_and_data_database_navigation.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 java_images_and_data_database_navigation().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton_Next;
    private javax.swing.JButton jButton_last;
    private javax.swing.JButton jButton_previous;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel_image;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea_description;
    private javax.swing.JTextField jTextField_id;
    private javax.swing.JTextField jTextField_name;
    // End of variables declaration                   
}

     
///////////////OUTPUT:
java database records navigate
Java & MySQL Data And Images First Next Previous Last



Share this

Related Posts

Previous
Next Post »