首页>Program>source

我已经在Swing Java中创建了一个使用JTable的GUI,现在我想通过分页向其中显示下一页信息.我应该怎么做?

最新回答
  • 5月前
    1 #

    在Swing JTable中分页看起来很不错。

    这是节选:

    As far as I remember the solution for this problem lies in the concept of paging: just retrieve the data that the user wants to see and nothing more. This also means you have to sometimes get extra data from the db server (or appserver) if your user scrolls down the list.

    Big was my surprise that there wasn't really an out-of-the-box solution (not even a copy- paste solution) for this problem. Anyone that knows one, please don't hesitate to extend my (rather limited) knowledge of the J2EE platform.

    So we dug in, and tried to build a solution ourselves. What we eventually came up with was an adapted TableModel class to takes care of the paging.

    p

    实现此目的的另一个选项是使用无滚动条的滚动窗格和几个导航按钮来实现控件.添加的按钮是普通 JButton s为原型。

    下面添加了一个快速原型.它有两个假设,其中之一是表模型具有所有数据.可以做一些工作来确保行在导航时最终排在视图的顶部。

    private void buildFrame() {
        frame = new JFrame("Demo");
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addStuffToFrame();
        frame.setVisible(true);
    }
    private void addStuffToFrame() {
        final JTable table = getTable();
        final JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        final JButton next = new JButton("next");
        final JButton prev = new JButton("prev");
        ActionListener al = new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                Rectangle rect = scrollPane.getVisibleRect();
                JScrollBar  bar = scrollPane.getVerticalScrollBar();
                int blockIncr = scrollPane.getViewport().getViewRect().height;
                if (e.getSource() == next) {
                    bar.setValue(bar.getValue() + blockIncr);
                } else if (e.getSource() == prev) {
                    bar.setValue(bar.getValue() - blockIncr);
                }
                scrollPane.scrollRectToVisible(rect);
            }
        };
        next.addActionListener(al);
        prev.addActionListener(al);
        JPanel panel = new JPanel(new BorderLayout());
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(prev);
        buttonPanel.add(next);
        panel.add(buttonPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        frame.getContentPane().add(panel);
    }
    private JTable getTable() {
        String[] colNames = new String[]{
                "col 0", "col 1", "col 2", "col 3"
        };
        String[][] data = new String[100][4];
        for (int i = 0; i < 100; i++) {
            for (int j = 0; j < 4; j++) {
                data[i][j] = "r:" + i + " c:" + j;
            }
        }
        return new JTable(data,colNames);
    }
    

    替代文字http://img7.imageshack.us/img7/4205/picture4qv.png

  • 5月前
    2 #

    您可以尝试使用2个查询,第一个查询是计算数据库中的总行,第二个查询是 对于real数据:)对于UI端,您可以这样尝试:

     
    
    public class MainForm extends javax.swing.JFrame {
       private void initDefaultValue() {
            rowsPerPage = Integer.valueOf(cmbPageSize.getSelectedItem().toString());
            totalRows = Main.getTablePagingService().countComments();
            Double dblTotPage = Math.ceil(totalRows.doubleValue()/rowsPerPage.doubleValue());
            totalPage = dblTotPage.intValue();
            if (pageNumber == 1) {
                btnFirst.setEnabled(false);
                btnPrevious.setEnabled(false);
            } else {
                btnFirst.setEnabled(true);
                btnPrevious.setEnabled(true);
            }
            if (pageNumber.equals(totalPage)) {
                btnNext.setEnabled(false);
                btnLast.setEnabled(false);
            } else {
                btnNext.setEnabled(true);
                btnLast.setEnabled(true);
            }
            txtPageNumber.setText(String.valueOf(pageNumber));
            lblPageOf.setText(" of " + totalPage + " ");
            lblTotalRecord.setText("Total Record " + totalRows + " rows.");
            List wPComments = Main.getTablePagingService().findAllComment(pageNumber, rowsPerPage);
            jTable1.setModel(new CommentTableModel(wPComments));
            autoResizeColumn(jTable1);
        }    
        private void btnFirstActionPerformed(ActionEvent evt) {
            pageNumber = 1; initDefaultValue();
        }
        private void btnPreviousActionPerformed(ActionEvent evt) {
            if (pageNumber >1) {
                pageNumber -= 1; initDefaultValue();
            }
        }
        private void btnNextActionPerformed(ActionEvent evt) {
            if (pageNumber

    And in service layer, you just need use limit function like this :

    public List findAllComment(Integer pageNumber, Integer rowsPerPage) {
            try {
                List listWP = new ArrayList();
                preparedFindAll.setInt(1, (rowsPerPage*(pageNumber-1)));
                preparedFindAll.setInt(2, rowsPerPage);
                ResultSet rs = preparedFindAll.executeQuery();
                while (rs.next()) {
                    WPComment comment = new WPComment();
                    comment.setCommentID(rs.getInt("comment_ID"));
                    comment.setCommentAuthor(rs.getString("comment_author"));
                    comment.setCommentDate(rs.getDate("comment_date"));
                    comment.setCommentContent(rs.getString("comment_content"));
                    listWP.add(comment);
                }
                return listWP;
            } catch (SQLException ex) {
                Logger.getLogger(TablePagingServiceJDBC.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
        public Integer countComments() {
            try {
                Integer totalRows = 0;
                ResultSet rs = preparedCount.executeQuery();
                while (rs.next()) {
                    totalRows = rs.getInt("count(*)");
                }
                return totalRows;
            } catch (SQLException ex) {
                Logger.getLogger(TablePagingServiceJDBC.class.getName()).log(Level.SEVERE, null, ex);
            }
            return 0;
        }
    

    或者您可以在Swing上的Project Page Table Paging上的github上分叉:)

  • 5月前
    3 #

    我已经编写了Java分页工具dataj.它使用JQuery dataTables插件分页元数据来构建结果页面。 我还为Java Swing添加了一些客户端类,其中包括TableRowSorter,该类调用(服务器端)排序,而不是在表模型内部进行排序。 如有任何疑问,请随时下载并与我联系.它已获得Apache 2许可。

  • 5月前
    4 #

    或者,您可以使用 QuickTable 项目。

    屏幕截图

    这是 DBTable 运作中的组件:

    维兹威兹 组件嵌入在传统的 DBTable

    示例代码

    以下示例代码将产生上一个屏幕快照中显示的窗口:

    JFrame
    
    资源和依赖项

    import javax.swing.JFrame; import javax.swing.UIManager; import quick.dbtable.DBTable; public class QuickTableFrame extends JFrame { private static final long serialVersionUID = -631092023960707898L; public QuickTableFrame() { try { // Use system look and feel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // set Frame properties setSize(300, 200); setVisible(true); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); // create a new quicktable DBTable dBTable1 = new DBTable(); // add to frame getContentPane().add(dBTable1); // set the database driver to be used, we are using jdbc-odbc driver dBTable1.setDatabaseDriver("org.h2.Driver"); /* * set the jdbc url,"quicktabledemo" is the data source we have * created for the database */ dBTable1.setJdbcUrl("jdbc:h2:mem:test;INIT=create table employee as select * from CSVREAD('test.csv');"); // set the select statement which should be used by the table dBTable1.setSelectSql("select * from employee"); // to create the navigation bars for the table dBTable1.createControlPanel(); // connect to database & create a connection dBTable1.connectDatabase(); // fetch the data from database to fill the table dBTable1.refresh(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // create a new table frame QuickTableFrame myframe = new QuickTableFrame(); } }

    test.csv
    

    empid,emp_name,emp_dept,emp_salary 1,Azalia,ornare,114918 2,Jade,tristique,152878 3,Willa,In scelerisque scelerisque,166733 ...

    H2
    
    参考文献 <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.187</version> </dependency>

      QuickTable basic tutorial

      QuickTable official tutorials

      Download latest jar

      h2 database

  • python:为什么map()和列表理解的结果不同?
  • Java Runtimeexec()