Pages

Tuesday, October 18, 2011

Retrieve Data from Database and Display Using JList

Program Description:

The Program below is a Java Code that demonstrates on how to retrieve data from MS Access database and display it using JList. It has five buttons that corresponds to the database fields you want to display in the JList. This technique is commonly used in many programs so I have created a simple and easy to understand java codes in order to understand the flow of the whole program easily. Always refer to "Important Part of the Program".

Download: retrieveDBUsingJList.rar

Output:
Code:

/**
 * File: retrieveDBUsingJList.java
 * Tiltle: Retrieve Database and Display Using JList
 * Author: http://java-program-sample.blogspot.com/
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJList extends JFrame {
 
 //Initializing program components
 private DefaultListModel model;
 private JButton buttons[];
 private JList dbList;
 private JPanel p1,p2;
 private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
 
 Connection con;
 Statement st;
 ResultSet rs;
 String db;

 //Setting up GUI
    public retrieveDBUsingJList() {
     
     //Setting up the Title of the Window
     super("Retrieve DB and Display Using JList");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(300,200);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          
     //Constructing JButtons, JList, and DefaultListModel
     model = new DefaultListModel();
     buttons = new JButton[5];
     dbList = new JList(model);
     
     //Setting up JList property
     dbList.setVisibleRowCount(5);
     dbList.setFixedCellHeight(27);
     dbList.setFixedCellWidth(130);
     dbList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  
  //Constructing JPanel 1 and its property
  p1 = new JPanel();
  p1.setBorder(BorderFactory.createTitledBorder("Database: "));
  p1.add(new JScrollPane(dbList)); //Adding JList in JPanel 1
  
  //Constructing JPanel 2 and its property
  p2 = new JPanel();
  p2.setLayout(new GridLayout(5,1));
  p2.setBorder(BorderFactory.createTitledBorder("Display: "));
  
  //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
  for(int count=0; count<buttons.length; count++) {
   buttons[count] = new JButton(bLabel[count]);
   p2.add(buttons[count]);
  }
  
  //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);

     //Setting up the container layout
     GridLayout grid = new GridLayout(1,2);
     pane.setLayout(grid);
     
     //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();  
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
    System.exit(0);
   }
   
  //Implemeting Even-Listener on JButton buttons[0] which is ID
  buttons[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("id"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[1] which is First Name
  buttons[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("firstName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
  buttons[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("middleName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[3] which is Last Name
  buttons[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("familyName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[4] which is Age
  buttons[4].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("age"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
        
     //Adding components to the container
  pane.add(p1);
  pane.add(p2);
  
     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
     setResizable(false);
    }
    
 //Main Method
    public static void main (String[] args) {
     retrieveDBUsingJList rdjl = new retrieveDBUsingJList();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JButton buttons[0] which is ID
  buttons[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("id"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[1] which is First Name
  buttons[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("firstName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
  buttons[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("middleName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[3] which is Last Name
  buttons[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("familyName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[4] which is Age
  buttons[4].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("age"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );