首頁>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()