How to scroll two or more JTables with a single Scrollbar?

…衆ロ難τιáo~ 提交于 2019-12-10 20:29:42

问题


How can I use one scroll from one JScrollPane to move another or more than one JScrollPane?

In example:

I have three JTables in separate JScrollPanes. I want to bind the scrollpanes to each other.

If I'll use one - the another will scroll the same way.

Some kind of Listeners which i can't find?

Any sugestions?

Best regards.


回答1:


An approach that preserves the JTables' headers would be to use the same BoundedRangeModel for each JScrollPane's vertical scrollbar and add each ScrollPane to a single JPanel.

class ParallelTables {
    static JScrollPane createTable() {
        DefaultTableModel model = new DefaultTableModel(100, 2);
        for (int row=model.getRowCount(); --row>=0;) {
            model.setValueAt(row, row, 0);
        }
        JTable table = new JTable(model);
        return new JScrollPane(table);
    }

    public static void main(String[] args) throws Exception {

        JScrollPane scrollerA = createTable();
        JScrollPane scrollerB = createTable();
        scrollerA.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        // the following statement binds the same BoundedRangeModel to both vertical scrollbars.
        scrollerA.getVerticalScrollBar().setModel(
                scrollerB.getVerticalScrollBar().getModel());
        JPanel panel = new JPanel();
        panel.add(scrollerA);
        panel.add(scrollerB);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

Reference:

  • https://forums.oracle.com/forums/thread.jspa?threadID=1348214



回答2:


I have three JTables in separate JScrollPanes. I want to "bound" scroll to each other.

Don't put the JTables in JScrollPanes. Put each JTable into a JPanel, and put the 3 JPanels into one JScrollPane.

It would probably be easier to combine your 3 JTables into one JTable.




回答3:


David Kroukamp's suggestion was to have the scrollbars share a model, like this:

    scrollerA.getVerticalScrollBar().setModel(
            scrollerB.getVerticalScrollBar().getModel());

That certainly works fine, but if you want to use a single scrollbar for all tables, it's even simpler to replace one scrollbar with the other:

    scrollerA.setVerticalScrollBar(
            scrollerB.getVerticalScrollBar());

Only one scrollbar appears with this method, and it scrolls both tables.



来源:https://stackoverflow.com/questions/12060587/how-to-scroll-two-or-more-jtables-with-a-single-scrollbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!