001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import java.awt.Container;
005import java.awt.Point;
006import java.awt.Rectangle;
007
008import javax.swing.JTable;
009import javax.swing.JViewport;
010import javax.swing.table.TableModel;
011
012/**
013 * Table offering easier scroll to a given row/column.
014 * @since 11881
015 */
016public class ScrollableTable extends JTable {
017
018    /**
019     * Constructs a <code>ScrollableTable</code> that is initialized with
020     * <code>dm</code> as the data model, a default column model,
021     * and a default selection model.
022     *
023     * @param dm the data model for the table
024     * @see #createDefaultColumnModel
025     * @see #createDefaultSelectionModel
026     */
027    public ScrollableTable(TableModel dm) {
028        super(dm);
029    }
030
031    /**
032     * Scrolls this table to make sure the (row,col) is visible.
033     * @param row row index
034     * @param col column index
035     */
036    public void scrollToVisible(int row, int col) {
037        Container parent = getParent();
038        if (parent instanceof JViewport) {
039            JViewport viewport = (JViewport) parent;
040            Rectangle rect = getCellRect(row, col, true);
041            Point pt = viewport.getViewPosition();
042            rect.setLocation(rect.x - pt.x, rect.y - pt.y);
043            viewport.scrollRectToVisible(rect);
044        }
045    }
046}