如何在Swing而不是滚动条中为JTable提供分页?

时间:2015-10-15 13:01:49

标签: java swing pagination jframe jtable

我一直在开发一个需要我在JTable中实现分页的应用程序。我使用Microsoft Access数据库中的数据填充JTable。所有这一切都很完美。我真的不知道如何在我的JTable中实现分页的概念。我的数据库中有超过15000条记录,所有15000条记录都显示在一个带滚动条的页面中,因此速度变慢,我希望每页显示50条记录。因此,当用户单击下一个按钮时,将显示接下来的50条记录,依此类推。 我在Swing Java中创建了GUI,其中我使用了JTable。我该怎么办? 这是我的jtable类,我获取数据并显示为jtable。

package com.ktech.voters;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.Vector;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author ahmad
 */
public class votersTable extends javax.swing.JFrame {

    DefaultTableModel dm;
    /**
     * Creates new form votersTable
     */
    private Vector<Vector<String>> data;
    private Vector<String> header; 

    public votersTable() throws Exception {
        votersDAO dao = new votersDAO();
        data = dao.getVoters();

        header = new Vector<String>();
        header.add("ID");
        header.add("Naam");
        header.add("walid ka naam");
        header.add("CNIC number");
        header.add("Polling Station Number");
        header.add("booth number");

        initComponents();
    }

    private void filter(String query)
    {
        dm = (DefaultTableModel) jTable1.getModel();
        TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(dm);
        jTable1.setRowSorter(tr);

        tr.setRowFilter(RowFilter.regexFilter(query));
    }

//    private void validator(String q)
//    {
//        if (q.matches(".*\\d.*"))
//        {
//            idSearch.setEditable(true);
//            idSearch.setBackground(Color.blue);
//        }
//        else 
//        {
//            idSearch.setEditable(false);
//            idSearch.setBackground(Color.red);
//        }
//
//        
//    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        idSearch = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            data,header
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Search by CNIC");

        idSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idSearchActionPerformed(evt);
            }
        });
        idSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                idSearchKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                idSearchKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                idSearchKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(90, 90, 90)
                        .addComponent(jLabel1)
                        .addGap(37, 37, 37)
                        .addComponent(idSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 939, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(77, 77, 77))
        );

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

    private void idSearchKeyReleased(java.awt.event.KeyEvent evt) {                                     

        String query=idSearch.getText();
        filter(query);
    }                                    

    private void idSearchKeyPressed(java.awt.event.KeyEvent evt) {                                    

//        String q=idSearch.getText();
//        validator(q);
        int key = evt.getKeyCode();
        if((key>=evt.VK_0&&key<=evt.VK_9)||(key>=evt.VK_NUMPAD0&&key<=evt.VK_NUMPAD9)
          ||key==KeyEvent.VK_BACK_SPACE||key==KeyEvent.VK_MINUS)
        {
            idSearch.setEditable(true);
        }
        else
        {
            idSearch.setEditable(false);
            idSearch.setBackground(Color.red);
        }
//        
//        
//        
//        if (check.matches(".*\\d.*"))
//        {
//            idSearch.setEditable(true);
//            idSearch.setBackground(Color.YELLOW);
//        }
//        else
//        {
//            idSearch.setEditable(false);
//            idSearch.setBackground(Color.red);
//        }

    }                                   

    private void idSearchKeyTyped(java.awt.event.KeyEvent evt) {                                  

//        String q=idSearch.getText();
//        validator(q);

    }                                 

    private void idSearchActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    /**
     * @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(votersTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(votersTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(votersTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(votersTable.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() {
                try
                {
                new votersTable().setVisible(true);
                }
                catch (Exception e)
                {
                    System.out.println("cannot run");
                }
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField idSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}

这是我的dao类,我在其中检索数据并在上面提到的jtable类中的jtable中显示。

import java.sql.Statement;
import java.util.Vector;


/**
 *
 * @author ahmad
 */
public class votersDAO extends dbUtility {

    private static Statement st;
    private static ResultSet rs;
        public Vector getVoters()throws Exception
        {
            Vector<Vector<String>> votersVector = new Vector<Vector<String>>();

            Connection connection = getConnection();
            st = connection.createStatement();
            rs = st.executeQuery("select * from Voters");

        while(rs.next())
        {
            Vector<String> voters = new Vector<String>();
            voters.add(rs.getString(1)); 
            voters.add(rs.getString(11));
            voters.add(rs.getString(12));
            voters.add(rs.getString(13));
            voters.add(rs.getString(17));
            voters.add(rs.getString(20));
            votersVector.add(voters);
        }

    if(connection!=null)
    connection.close();

return votersVector;
}
请你帮我们帮助我。任何可以与我的代码合并的例子都会有所帮助。

0 个答案:

没有答案