1

I have a JTable in a JScrollPane. If the screen shows half of a row in the JTable, when clicking on the JTable, the JScrollPane scrolls automatically to show the entire row.

How do I stop that behavior, such that a click will not scroll the JScrollPane.

Thanks!

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
DudiD
  • 215
  • 2
  • 7
  • 16

1 Answers1

2

The behavior is enforced by calling scrollRectToVisible() from the table's UI delegate, typically derived from BasicTableUI. Short of supplying your own delegate, you can use setPreferredScrollableViewportSize() to make the height of enclosing Container an intergral multiple of the rowHeight, as shown below and in this example.

private static final int N_ROWS = 8;
private JTable table = new JTable();
...
Dimension d = new Dimension(
    table.getPreferredScrollableViewportSize().width,
    N_ROWS * table.getRowHeight());
table.setPreferredScrollableViewportSize(d);
add(new JScrollPane(table));

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    you know what I think about hard-coding sizes ;-) SetPrefScrollable is not much different from any of the other setXXSize. Instead, implement the table's getPreferredScrollableViewportSize to return something reasonable, f.i. in terms of configurable properties like visible rows/columns (as JXTable does :-) – kleopatra Jun 26 '12 at 09:18
  • @kleopatra: Exactly right, as discussed [here](http://stackoverflow.com/q/7229226/230513) and shown in this related [example](http://stackoverflow.com/a/11132778/230513). – trashgod Jun 26 '12 at 15:06