JTable Connection with JDBC-MYSQL and Pagination Over JTable

Today I show you how to use the JTable and pagination over the JTable

for the data representation on the java swing.


JTable is the java swing component which show the data on tabular format on the two-dimensional tables of cells.



public class Jtable extends JComponent

JTable display large data at a time but it take some time to load the data so for that I have used the pagination over the table and the records are displayed on the number of pages.



I used the netbean IDE 7.0.1 for the UI development



I create the Jtable , and stored the data from the mysql DB. And paging the data...




DefaultTableModel Tbl_Model;

DefaultListModel Tbl_List;

ResultSetMetaData metaDt_first;

private javax.swing.JTable tbl_result;

Statement st_bookingTable;
ResultSet  rs_bookingTable;

// Following variables are used for the paging.

TableRowSorter<TableModel> sorter;

private static int LR_PAGE_SIZE = 5;

private final Box box = Box.createHorizontalBox();

private static final LinkViewRadioButtonUI ui = new LinkViewRadioButtonUI();

private static final Color evenColor = new Color(240, 255, 250);

The following function make a connection with database and select the data from DB and create paging over the jtable.


public void Fill_table()
{

try {
         String sql_bookingTable;
          int Col_count;
          Tbl_Model = null;
          Tbl_List = null;
          metaDt_first = null;
          st_bookingTable = null;
          rs_bookingTable = null;
          Tbl_Model = new DefaultTableModel();
          Tbl_List = new DefaultListModel();
          st_bookingTable = (Statement) objMenus.db_con.createStatement();

 
// db_con is the function where I make a jdbc-mysql connection on another class
// you may the db_con function click here


          String cons_name;
          String sql_Const_query = "select * from Booking";
          rs_bookingTable = (ResultSet) st_bookingTable.executeQuery(sql_Const_query);
          metaDt_first = (ResultSetMetaData) rs_bookingTable.getMetaData();
          Col_count = metaDt_first.getColumnCount();
          int[] columnsWidth = {30, 30, 30, 30, 30, 30, 30};
          for (int i = 1; i < Col_count + 1; i++)
          {
                    Tbl_Model.addColumn(metaDt_first.getColumnName(i).toUpperCase());
                    Tbl_List.addElement(metaDt_first.getColumnName(i).toUpperCase());
          }
          while (rs_bookingTable.next()) 
          {
                    Object[] rowData = new Object[Col_count];
                    for (int i = 0; i < rowData.length; ++i)
                    {
                              rowData[i] = rs_bookingTable.getObject(i + 1);
                    }
                   Tbl_Model.addRow(rowData);

          }

          tbl_result.setModel(Tbl_Model);

          lbl_rowCount.setText("No of Table Rows " + Tbl_Model.getRowCount());

          tbl_result.getTableHeader().getColumnModel().getColumn(0).setHeaderValue("Booking Id");

         tbl_result.getTableHeader().getColumnModel().getColumn(1).setHeaderValue("Supplier");

          tbl_result.getTableHeader().getColumnModel().getColumn(2).setHeaderValue("Amount");

          tbl_result.getTableHeader().getColumnModel().getColumn(3).setHeaderValue("Supplier Rate");

          tbl_result.getTableHeader().getColumnModel().getColumn(4).setHeaderValue("Service Date");

          tbl_result.getTableHeader().getColumnModel().getColumn(5).setHeaderValue("Agent Name");

          tbl_result.getTableHeader().getColumnModel().getColumn(6).setHeaderValue("Agency Name");

          for(int kk=0;kk<tbl_result.getColumnCount();kk++)
          {
              tbl_result.getTableHeader().getColumnModel().getColumn(kk).setPreferredWidth(260);
          }

          tbl_result.invalidate();
          //for the paging
          sorter = new TableRowSorter<TableModel>(Tbl_Model);
          tbl_result.setRowSorter(sorter);

// This function create the paging over the Jtable It will show first 100 records from database

          initLinkBox(100, 1); 

   } catch (Exception e) {
          System.out.println("Error at filling table " + e);
          e.printStackTrace();

    }

}

The following function take the number of data which you want to show on per page and the current page index is must be 1 so it start from the first record of a database


private void initLinkBox(final int itemsPerPage, final int currentPageIndex) 
{
       sorter.setRowFilter(makeRowFilter(itemsPerPage, currentPageIndex-1));
       ArrayList<JRadioButton> paginationButtons = new ArrayList<JRadioButton>();
        int startPageIndex = currentPageIndex-LR_PAGE_SIZE;
        if(startPageIndex<=0) startPageIndex = 1;
        int rowCount = Tbl_Model.getRowCount();
        int v = rowCount%itemsPerPage==0 ? 0 : 1;
         int maxPageIndex = rowCount/itemsPerPage + v;
         int endPageIndex = currentPageIndex+LR_PAGE_SIZE-1;
          if(endPageIndex>maxPageIndex) endPageIndex = maxPageIndex;
          if(currentPageIndex>1) 
          {
           paginationButtons.add(makePNRadioButton(itemsPerPage, currentPageIndex-1, "Prev |      "));

  }

if(startPageIndex<endPageIndex)
 {
          for(int i=startPageIndex;i<=endPageIndex;i++) {
          paginationButtons.add(makeRadioButton(itemsPerPage, currentPageIndex, i-1));

   }

}

if(currentPageIndex<maxPageIndex) 
{
          paginationButtons.add(makePNRadioButton(itemsPerPage, currentPageIndex+1, " | Next"));

}

          box.removeAll();
          ButtonGroup bg = new ButtonGroup();
          box.add(Box.createHorizontalGlue());
          for(JRadioButton r:paginationButtons) 
          {
                    box.add(r);
                    bg.add(r);
          }
          box.add(Box.createHorizontalGlue());
          box.revalidate();
          box.repaint();
          paginationButtons.clear();

}


The following function make the number of pages and give it to the colors as a blue for unselect page and make a read color for the selected page



private JRadioButton makePNRadioButton(final int itemsPerPage, final int target, String title) 
{

          JRadioButton radio = new JRadioButton(title);
          radio.setForeground(Color.BLUE);
          radio.setUI(ui);
          radio.addActionListener(new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) 
          {
               initLinkBox(itemsPerPage, target);

          }

          });

          return radio;

}

private RowFilter<TableModel,Integer> makeRowFilter(final int itemsPerPage, final int target)
 {
          return new RowFilter<TableModel,Integer>() {

          @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry)   
           {
                    int ei = entry.getIdentifier();
                    return target*itemsPerPage<=ei && ei<target*itemsPerPage+itemsPerPage;

            }

          };

}

private JRadioButton makeRadioButton(final int itemsPerPage, final int current, final int target) 
{

          JRadioButton radio = new JRadioButton(String.valueOf(" "+(target+1)+" ") )
          {
              @Override 
             protected void fireStateChanged() 
            {
                  ButtonModel model = getModel();
                if(!model.isEnabled()) 
               {

                    setForeground(Color.GRAY);

                }
               else if(model.isPressed() && model.isArmed()) 
               {
                    setForeground(Color.GREEN);
               }
              else if(model.isSelected()) 
              {
                    setForeground(Color.RED);
              }
                    super.fireStateChanged();

              }

          };

          radio.setForeground(Color.BLUE);
          radio.setUI(ui);
          if(target+1==current) 
         {

             radio.setSelected(true);
          }
          radio.addActionListener(new ActionListener() 
          {

                    @Override
                   public void actionPerformed(ActionEvent e)
                   {
                          initLinkBox(itemsPerPage, target+1);
                   }

          });
       return radio;

}






// The output is as follows...





Comments

  1. I could ask whether the full source code?? I've tried but have not succeeded. please me. if you can please send to my email wilfridus.laki @ yahoo.com

    ReplyDelete
    Replies

    1. Please check your email I sent you the source code.

      Delete
  2. Can you please upload the full source code to google documents so that we can easily download it.. Thanks in advance...

    ReplyDelete
  3. Please provide me the full source code. My mail : dsatishshah@gmail.com

    ReplyDelete
  4. Please help me with full source code Mail me : aalagurajan@gmail.com

    ReplyDelete
  5. Hello please assist me with full source code. my email; helbert.hilly@yahoo.com

    ReplyDelete
  6. Hello, please send me the full code. I have tried but I couldn't get it to work in my own application

    ReplyDelete
  7. plese sir, my email e61permana@gmail.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Database connection with mysql in Java

JAVA Chart