How to get all visible rows of JTable model within a JScrollPane

3.5k Views Asked by At

So far I know how to get a particular row at a point using the JScrollPane's JViewPort object.

scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {

        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            JViewport viewport = scrollPane.getViewport();
            Point p = viewport.getViewPosition();
            int rowIndex = getLogsTable().rowAtPoint(p);
            System.out.println("Minimum Y: " + viewport.getViewRect().getMinY());
            System.out.println("Min row: " + getLogsTable().rowAtPoint(new Point(0, (int) viewport.getViewRect().getMinY())));
            System.out.println("Maximum Y: " + viewport.getViewRect().getMaxY());
            System.out.println("Max row: " + getLogsTable().rowAtPoint(new Point(0, (int) viewport.getViewRect().getMaxY())));
        }

    });

I am having a tough time figuring out how to get all the rows between the JViewport.getMinimumY() and JViewport.getMaximumY(). Is there a way to gather all row items between those two viewport points or is there any way to just get all rows in the JScrollPane view?

1

There are 1 best solutions below

1
On

Based on @dic19's comment, I used that snippet of code, and it worked. I just added an extra variable to handle retrieving the last row index number.

// need to wait for table to fully load
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            // getLogsTable() returns JTable instance
            Rectangle vr = getLogsTable().getVisibleRect();
            int firstRow = getLogsTable().rowAtPoint(vr.getLocation());
            vr.translate(0, vr.height);
            int visibleRows = getLogsTable().rowAtPoint(vr.getLocation()) - firstRow;
            int lastRow = (visibleRows > 0) ? visibleRows+firstRow : getLogsTable().getRowCount();

            System.out.println("first visible row: " + firstRow + " last visible row: " + lastRow);

            for(int rowNum=firstRow+1; rowNum<=lastRow; rowNum++) {
                    // LogsModel is a AbstractTableModel instance
                    LogsModel model = (LogsModel) getLogsTable().getModel();
                    Log log = model.getData().get(getLogsTable().convertRowIndexToModel(rowNum-1));
                    System.out.println(log.getLocation());
            }

            System.out.println(lastRow);
        }

    });