Haircuts Are Important said:
The capability that I am trying to get is this. I have two
tables with the right one being a lot larger than the left
one. What I have been attempting to do is scroll the right
table vertically and have the left table scroll vertically at
the same time.
Summarizing some of my earlier suggestions on shared models and timers,
the sscce below illustrates how I would proceed. I've also used the
event dispatch thread and shown an alternate approach to scrolling.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
class ParallelTables {
private final DefaultTableModel modelA = initModel(1);
private JTable tableA = new JTable(modelA) {
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension d = super.getPreferredScrollableViewportSize();
return new Dimension(d.width / 2, d.height);
}
};
private final DefaultTableModel modelB = initModel(5);
private JTable tableB = new JTable(modelB);
private DefaultTableModel initModel(int n) {
DefaultTableModel model = new DefaultTableModel(100, n);
for (int row = 0; row < model.getRowCount(); row++) {
model.setValueAt(row, row, 0);
}
return model;
}
private void display() {
final JScrollPane scrollA = new JScrollPane(tableA);
JScrollPane scrollB = new JScrollPane(tableB);
scrollA.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollA.getVerticalScrollBar().setModel(
scrollB.getVerticalScrollBar().getModel());
tableA.setSelectionModel(tableB.getSelectionModel());
JPanel panel = new JPanel(
new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(scrollA);
panel.add(scrollB);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
int last = modelA.getRowCount() - 1;
tableA.getSelectionModel().setSelectionInterval(last, last);
tableA.scrollRectToVisible(
tableA.getCellRect(last, last, true));
Timer t = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modelA.addRow(new Object[]{42});
modelB.addRow(new Object[]{42, 42, 42, 42, 42});
int last = modelA.getRowCount() - 1;
tableA.scrollRectToVisible(
tableA.getCellRect(last, last, true));
}
});
t.setInitialDelay(0);
t.start();
}
public static void main(String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ParallelTables().display();
}
});
}
}