RowAdder.java Source code

Java tutorial

Introduction

Here is the source code for RowAdder.java

Source

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

public class RowAdder extends JFrame {
    SimpleModel tableData = new SimpleModel();
    JTable table = new JTable(tableData);

    public static void main(String[] args) {
        RowAdder ra = new RowAdder();
        ra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ra.setSize(400, 300);
        ra.setVisible(true);
    }

    public RowAdder() {
        setLayout(new BorderLayout());
        table.addComponentListener(new TableScroller());
        add(new JScrollPane(table), BorderLayout.CENTER);
    }

    class TableScroller extends ComponentAdapter {

        public void componentResized(ComponentEvent event) {
            int lastRow = tableData.getRowCount() - 1;
            int cellTop = table.getCellRect(lastRow, 0, true).y;
            JScrollPane jsp = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, table);
            JViewport jvp = jsp.getViewport();
            int portHeight = jvp.getSize().height;
            int position = cellTop - (portHeight - table.getRowHeight() - table.getRowMargin());
            if (position >= 0) {
                jvp.setViewPosition(new Point(0, position));
            }
        }
    }
}

class SimpleModel extends AbstractTableModel {

    public void addText(String text) {
        fireTableDataChanged();
    }

    public int getRowCount() {
        return 100;
    }

    public int getColumnCount() {
        return 3;
    }

    public Object getValueAt(int row, int column) {
        return row + " " + column;
    }

}