Google Tag Manager

2015/09/30

Adjust the height of every row in the JTable to fit the JViewport

Code

JTable table = new JTable(model) {
  int prevHeight = -1;
  int prevCount = -1;
  public void updateRowsHeigth(JViewport vport) {
    int height = vport.getExtentSize().height;
    int rowCount = getModel().getRowCount();
    int defautlRowHeight = height / rowCount;
    if ((height != prevHeight || rowCount != prevCount) && defautlRowHeight > 0) {
      int over = height - rowCount * defautlRowHeight;
      for (int i = 0; i < rowCount; i++) {
        int a = over-- > 0 ? i == rowCount - 1 ? over : 1 : 0;
        setRowHeight(i, defautlRowHeight + a);
      }
    }
    prevHeight = height;
    prevCount = rowCount;
  }
  @Override public void doLayout() {
    super.doLayout();
    Container p = SwingUtilities.getAncestorOfClass(JViewport.class, this);
    if (p instanceof JViewport) {
      updateRowsHeigth((JViewport) p);
    }
  }
};

References

No comments:

Post a Comment