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

java, jscrollpane, jtable, swing

Solution

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

Problem

How can I use one scroll from one `JScrollPane` to move another or more than one `JScrollPane`? In example: I have three `JTable`s in separate `JScrollPane`s. I want to bind the scrollpanes to each other. If I'll use one - the another will scroll the same way. Some kind of `Listener`s which i can't find? Any sugestions? Best regards.

Original source