如何为 Swing 中的 JTable 提供分页支持? [英] How to provide pagination support to a JTable in Swing?

查看:51
本文介绍了如何为 Swing 中的 JTable 提供分页支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created one GUI in Swing Java in which I have used JTable.Now I want to display next page information into it by using pagination. How should I do that ?

推荐答案

实现这一点的另一个选择是使用无滚动条的滚动窗格和几个导航按钮来实现控制.添加的按钮是原型的普通JButton.

Another option to implement this is to use a scrollbar-less scrollpane and a couple nav buttons to effect the control. The buttons that have been added are normal JButtons for the prototype.

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

A quick prototype is added below. It makes a couple assumptions, one of which is that the table model has all of its data. Work could be done to ensure that rows end up flush at the top of the view upon navigation.

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

这篇关于如何为 Swing 中的 JTable 提供分页支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆