17 June 2011

MySQL Dynamic Data in JTable Tutorial


MySQL  Data in JTable Tutorial
Hello Friends,

Nice to see you again.
  • In Previous Sessions  we have seen lots of  Java Swing 
Components Demo. And learn how they work.
  • Today, we will see the example of  showing data from 
MySql Database into JTable of Java Swing.

  • Normally we have to develop application which have requirement 
to show Reports depends on database.
  • In this type of situations, We can use JTable with showing 
data from Database in it.

As there is no such direct method which provide you this facility at 
once. So we have to write some sort of code to enable of filling JTable with 
Data from Database.

It is very easy to understand the code for this.

  • First remember that to fill JTable with any data, we required to
create one Model which holds actual Data and the Headers 
of Columns.
  • So we here create one Default Table Model model and add two 
parameters data and header in it.
  • Now these both parameters (Data,Header) must be in int or 
Object or in Vector Format only.
  • Here I choose Vector as it is easy to fill it with Data from Database.
  • Now simply pass that Vectors in Constructor of DefaultTableModel,
          and apply that model to your JTable. Thats it...

    Here I have used MySQl database called 'test' and a table called 'one' as 
    shown below.







    So be ready to learn this simple exmaple of MySQl Data in JTable.
    After apply this code in action, you will be capable of using MySql
    Database in your JTable based Swing Applications.

    Output will be like this:












    OK For this you have to create one class called  dataInJTable.java and paste 
    the below code in it.
    And run it....Simple right..?




    ------------------------------------------------------------------------------------------------------------------------------------------------

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;

    public class dataInJTable extends JFrame{

    //This Vector Of A String Vector will be used to hold data from 
    // database table to display in JTable.
    static Vector<Vector<String>> data=new Vector<Vector<String>>();
    static JTable table;
    public dataInJTable()
    {
    super("JTabe with MySql Database");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel topPanel=new JPanel();
    JLabel label1=new JLabel("MySQL Database Name  :   test");
    label1.setPreferredSize(new Dimension(200,30));
    JLabel label2=new JLabel("MySQL Table Name     :  One");
    label2.setPreferredSize(new Dimension(200,30));
    topPanel.add(label1);
    topPanel.add(label2);
    getContentPane().add(topPanel,BorderLayout.NORTH);
    Vector<String> headers=new Vector<String>();
    headers.add("id");
    headers.add("Name");

    getData();
    //this is the model which contain actual body of JTable
    DefaultTableModel model = new DefaultTableModel(data, headers);
    table=new JTable(model);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    header_size();
    JScrollPane scroll = new JScrollPane(table);
    scroll.setHorizontalScrollBarPolicy(
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    getContentPane().add(scroll,BorderLayout.SOUTH);
    pack();
    setResizable(false);
    setVisible(true);
    }
    /**
    * Setting the particular Column Size in JTable
    */
    public static void header_size() {
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setPreferredWidth(100);

            column = table.getColumnModel().getColumn(1);
            column.setPreferredWidth(350);

         }
    /**
    * Fetching Data From MySql Database 
    * and storing in a Vector of a Vector
    * to Display in JTable
    */
    private static void getData()
    {
    // Enter Your MySQL Database Table name in below Select Query.
    String str="select * from one";
    Connection cn;
    ResultSet rs;
    Statement st;
    try {
    // Change the database name, hosty name, 
    // port and password as per MySQL installed in your PC.
    cn=DriverManager.getConnection("jdbc:mysql://" +
    "localhost:3306/test","root","root");
    st=cn.createStatement();
    rs=st.executeQuery(str);
    while(rs.next())
    {
    Vector <String> d=new Vector<String>();
    d.add(rs.getString("id"));
    d.add(rs.getString("name"));
    d.add("\n\n\n\n\n\n\n");
    data.add(d);
    }
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    public static void main(String[] args) {
    new dataInJTable();
    }

    }
    --------------------------------------------------------------------

    So I hope this code is helpful in understanding the working of JTable 
    with data from MySql Database.

    Feel free to ask me if you have any dought regarding this.
    You can also give me suggessions to improve this tutorial.

    Leave comments if you like this post...!

    Thank you.
    Nirav Raval

    6 June 2011

    MySQL Data in JTable Tutorial


    MySQL  Data in JTable Tutorial
    Hello Friends,

    Nice to see you again.
    • In Previous Sessions  we have seen lots of  Java Swing 
    Components Demo. And learn how they work.
    • Today, we will see the example of  showing data from 
    MySql Database into JTable of Java Swing.

    • Normally we have to develop application which have requirement 
    to show Reports depends on database.
    • In this type of situations, We can use JTable with showing 
    data from Database in it.

    As there is no such direct method which provide you this facility at 
    once. So we have to write some sort of code to enable of filling JTable with 
    Data from Database.

    It is very easy to understand the code for this.

    • First remember that to fill JTable with any data, we required to
    create one Model which holds actual Data and the Headers 
    of Columns.
    • So we here create one Default Table Model model and add two 
    parameters data and header in it.
    • Now these both parameters (Data,Header) must be in int or 
    Object or in Vector Format only.
    • Here I choose Vector as it is easy to fill it with Data from Database.
    • Now simply pass that Vectors in Constructor of DefaultTableModel,
              and apply that model to your JTable. Thats it...

      Here I have used MySQl database called 'test' and a table called 'one' as 
      shown below.







      So be ready to learn this simple exmaple of MySQl Data in JTable.
      After apply this code in action, you will be capable of using MySql
      Database in your JTable based Swing Applications.

      Output will be like this:












      OK For this you have to create one class called  dataInJTable.java and paste 
      the below code in it.
      And run it....Simple right..?



      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd">
      <bean id="helloWorld" class="com.test.HelloWorld">
      <property name="message" value="Hello World.!">
                                    </property>
      <property name="name" value="Nirav Raval!">
                                   </property>
      </bean>
      </beans>


      ------------------------------------------------------------------------------------------------------------------------------------------------

      import java.awt.BorderLayout;
      import java.awt.Dimension;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      import java.sql.Statement;
      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.util.Vector;
      import javax.swing.JFrame;
      import javax.swing.JLabel;
      import javax.swing.JPanel;
      import javax.swing.JScrollPane;
      import javax.swing.JTable;
      import javax.swing.table.DefaultTableModel;
      import javax.swing.table.TableColumn;

      public class dataInJTable extends JFrame{

      //This Vector Of A String Vector will be used to hold data from 
      // database table to display in JTable.
      static Vector<Vector<String>> data=new Vector<Vector<String>>();
      static JTable table;
      public dataInJTable()
      {
      super("JTabe with MySql Database");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel topPanel=new JPanel();
      JLabel label1=new JLabel("MySQL Database Name  :   test");
      label1.setPreferredSize(new Dimension(200,30));
      JLabel label2=new JLabel("MySQL Table Name     :  One");
      label2.setPreferredSize(new Dimension(200,30));
      topPanel.add(label1);
      topPanel.add(label2);
      getContentPane().add(topPanel,BorderLayout.NORTH);
      Vector<String> headers=new Vector<String>();
      headers.add("id");
      headers.add("Name");

      getData();
      //this is the model which contain actual body of JTable
      DefaultTableModel model = new DefaultTableModel(data, headers);
      table=new JTable(model);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      header_size();
      JScrollPane scroll = new JScrollPane(table);
      scroll.setHorizontalScrollBarPolicy(
      JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      scroll.setVerticalScrollBarPolicy(
      JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
      getContentPane().add(scroll,BorderLayout.SOUTH);
      pack();
      setResizable(false);
      setVisible(true);
      }
      /**
      * Setting the particular Column Size in JTable
      */
      public static void header_size() {
              TableColumn column = table.getColumnModel().getColumn(0);
              column.setPreferredWidth(100);

              column = table.getColumnModel().getColumn(1);
              column.setPreferredWidth(350);

           }
      /**
      * Fetching Data From MySql Database 
      * and storing in a Vector of a Vector
      * to Display in JTable
      */
      private static void getData()
      {
      // Enter Your MySQL Database Table name in below Select Query.
      String str="select * from one";
      Connection cn;
      ResultSet rs;
      Statement st;
      try {
      // Change the database name, hosty name, 
      // port and password as per MySQL installed in your PC.
      cn=DriverManager.getConnection("jdbc:mysql://" +
      "localhost:3306/test","root","root");
      st=cn.createStatement();
      rs=st.executeQuery(str);
      while(rs.next())
      {
      Vector <String> d=new Vector<String>();
      d.add(rs.getString("id"));
      d.add(rs.getString("name"));
      d.add("\n\n\n\n\n\n\n");
      data.add(d);
      }
      } catch (SQLException e) {
      e.printStackTrace();
      }
      }
      public static void main(String[] args) {
      new dataInJTable();
      }

      }
      --------------------------------------------------------------------

      So I hope this code is helpful in understanding the working of JTable 
      with data from MySql Database.

      Feel free to ask me if you have any dought regarding this.
      You can also give me suggessions to improve this tutorial.

      Leave comments if you like this post...!

      Thank you.
      Nirav Raval