Java SwingUtilities get Ancestor for a component

Description

Java SwingUtilities get Ancestor for a component


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 Main extends JFrame {
   SimpleModel tableData = new SimpleModel();
   JTable table = new JTable(tableData);

   public static void main(String[] args) {
      Main ra = new Main();
      ra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ra.setSize(400, 300);/*from  ww w  .  j ava2  s.  c  o m*/
      ra.setVisible(true);
   }

   public Main() {
      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;
   }
}



PreviousNext

Related