Java examples for Swing:JTable Column
Adjusts the JTable column width of the row headers table containing the number column.
import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Point; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.plaf.UIResource; import javax.swing.table.AbstractTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; public class Main{ /**/*from w w w.ja v a 2 s . co m*/ * Adjusts the column width of the row headers table containing the number * column. The font metrics are extracted from the label of the row at the * bottom of the viewport and used to determing the appropriate width. * * The reason why this method is important, is that when the row number increases by an extra digit * the column needs to get wider. It also needs to shrink when scrolling to smaller digit numbers. * * @param rowHeadersTable - single column table in the row header * @param label - label used to get font metrics * @param scrollBarValue - int value for determing point of lowest row */ private static void adjustColumnWidth(final JTable rowHeadersTable, final JLabel label, int scrollBarValue) { label.setFont(rowHeadersTable.getFont()); label.setOpaque(true); label.setHorizontalAlignment(JLabel.CENTER); int v = rowHeadersTable.getVisibleRect().height; int row = rowHeadersTable.rowAtPoint(new Point(0, v + scrollBarValue)); Integer modelValue = null; if (row != -1) { modelValue = (Integer) rowHeadersTable.getModel().getValueAt( row, 0); } else { RowHeadersTableModel tm = (RowHeadersTableModel) rowHeadersTable .getModel(); modelValue = new Integer(tm.getMaxIntValue()); } label.setText("" + modelValue); FontMetrics fontMetrics = label.getFontMetrics(label.getFont()); int widthFactor = 0; if (fontMetrics != null && label.getText() != null) { widthFactor = fontMetrics.stringWidth(label.getText()); rowHeadersTable .setPreferredScrollableViewportSize(new Dimension( widthFactor + 8, 100)); // height // is // ignored rowHeadersTable.repaint(); } } }