问题
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.
回答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