下面列出了javax.swing.table.TableColumn#getPreferredWidth ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Dimension getPreferredScrollableViewportSize() {
if( needCalcRowHeight ) {
calcRowHeight( getOffscreenGraphics() );
prefSize = null;
}
if( null == prefSize ) {
Dimension dim = new Dimension();
for( int i=0; i<getColumnCount(); i++ ) {
TableColumn tc = getColumnModel().getColumn( i );
dim.width += tc.getPreferredWidth();
}
int rowCount = Math.min( MAX_VISIBLE_ROWS, getRowCount() );
dim.height = rowCount*getRowHeight();
Rectangle screen = Utilities.getUsableScreenBounds();
dim.width = Math.min( dim.width, screen.width-100 );
dim.height = Math.min( dim.height, screen.height-100 );
prefSize = dim;
}
return prefSize;
}
private void updateTableColumnSizes() {
ETable table = tableView.getTable();
Font font = tableView.getFont();
FontMetrics fm = tableView.getFontMetrics(font);
int maxCharWidth = fm.charWidth('A');
int editingBorder = 4;
TableColumnModel columnModel = table.getColumnModel();
TableColumn nameColumn = columnModel.getColumn(0);
nameColumn.setPreferredWidth(8 * maxCharWidth + editingBorder); // 8 chars for name
TableColumn keyColumn = columnModel.getColumn(1);
// Single char for key (but 3 chars to prevent "..." in column header)
keyColumn.setPreferredWidth(3 * maxCharWidth + editingBorder);
keyColumn.setMinWidth(keyColumn.getPreferredWidth());
TableColumn locationColumn = columnModel.getColumn(2);
Insets insets = tableView.getBorder().getBorderInsets(tableView);
int remainingWidth = tableView.getParent().getWidth() - insets.left - insets.right;
remainingWidth -= 2 * columnModel.getColumnMargin();
remainingWidth -= nameColumn.getPreferredWidth();
remainingWidth -= keyColumn.getPreferredWidth();
locationColumn.setPreferredWidth(remainingWidth); // remaining space for location
}
private static int calcMaxWidth(JTable table) {
int colsNum = table.getColumnModel().getColumnCount();
int totalWidth = 0;
for (int col = 0; col < colsNum - 1; col++) {
TableColumn column = table.getColumnModel().getColumn(col);
int preferred = column.getPreferredWidth();
int width = Math.max(preferred, columnMaxWidth(table, col));
totalWidth += width;
column.setMinWidth(width);
column.setMaxWidth(width);
column.setWidth(width);
column.setPreferredWidth(width);
}
totalWidth += columnMaxWidth(table, colsNum - 1);
return totalWidth;
}
private static int calcMaxWidth(JTable table) {
int colsNum = table.getColumnModel().getColumnCount();
int totalWidth = 0;
for (int col = 0; col < colsNum - 1; col++) {
TableColumn column = table.getColumnModel().getColumn(col);
int preferred = column.getPreferredWidth();
int width = Math.max(preferred, columnMaxWidth(table, col));
totalWidth += width;
column.setMinWidth(width);
column.setMaxWidth(width);
column.setWidth(width);
column.setPreferredWidth(width);
}
totalWidth += columnMaxWidth(table, colsNum - 1);
return totalWidth;
}
private static int calcMaxWidth(JTable table) {
int colsNum = table.getColumnModel().getColumnCount();
int totalWidth = 0;
for (int col = 0; col < colsNum -1; col++) {
TableColumn column = table.getColumnModel().getColumn(col);
int preferred = column.getPreferredWidth();
int width = Math.max(preferred, columnMaxWidth(table, col));
totalWidth += width;
column.setMinWidth(width);
column.setMaxWidth(width);
column.setWidth(width);
column.setPreferredWidth(width);
}
totalWidth += columnMaxWidth(table, colsNum - 1);
return totalWidth;
}
/**
* Return the preferred size of the table. The preferred height is the row height times the number of rows. The
* preferred width is the sum of the preferred widths of each column.
*/
public Dimension getPreferredSize(final JComponent c) {
long width = 0;
Enumeration<TableColumn> enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createTableSize(width);
}
public Dimension getPreferredSize(JComponent c) {
long width = 0;
Enumeration<?> enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn aColumn = (TableColumn) enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createHeaderSize(width);
}
public DataTable(TableModel model) {
super(model);
setSurrendersFocusOnKeystroke(true);
TableColumnModel cmodel = getColumnModel();
int i;
int ccount = model.getColumnCount();
int columnWidth;
int preferredWidth;
String columnName;
int width = 0;
for (i = 0; i < ccount; i++) {
TableColumn col = cmodel.getColumn(i);
Map cmap = ColumnItem.getColumnProperty(i);
col.setIdentifier(cmap.get("name")); //NOI18N
columnName = NbBundle.getMessage (CreateTableDialog.class, "CreateTable_" + i); //NOI18N
columnWidth = (new Double(getFontMetrics(getFont()).getStringBounds(columnName, getGraphics()).getWidth())).intValue() + 20;
if (cmap.containsKey("width")) { // NOI18N
if (((Integer)cmap.get("width")).intValue() < columnWidth)
col.setPreferredWidth(columnWidth);
else
col.setPreferredWidth(((Integer)cmap.get("width")).intValue()); // NOI18N
preferredWidth = col.getPreferredWidth();
}
if (cmap.containsKey("minwidth")) // NOI18N
if (((Integer)cmap.get("minwidth")).intValue() < columnWidth)
col.setMinWidth(columnWidth);
else
col.setMinWidth(((Integer)cmap.get("minwidth")).intValue()); // NOI18N
// if (cmap.containsKey("alignment")) {}
// if (cmap.containsKey("tip")) ((JComponent)col.getCellRenderer()).setToolTipText((String)cmap.get("tip"));
if (i < 7) { // the first 7 columns should be visible
width += col.getPreferredWidth();
}
}
width = Math.min(Math.max(width, 380), Toolkit.getDefaultToolkit().getScreenSize().width - 100);
setPreferredScrollableViewportSize(new Dimension(width, 150));
}
/**
* Invokes the getPreferredSize method on each UI handled by this object.
*
* @param c the component whose preferred size is being queried; this
* argument is ignored.
* @return the dimension of the whole header
*/
@SuppressWarnings("unchecked")
public Dimension getPreferredSize(JComponent c) {
long width = 0;
Enumeration columns = header.getColumnModel().getColumns();
while (columns.hasMoreElements()) {
TableColumn aColumn = (TableColumn) columns.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createHeaderSize(width);
}
public Dimension getPreferredSize(JComponent c) {
long width = 0;
Enumeration<?> enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn aColumn = (TableColumn) enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createHeaderSize(width);
}
/** Resize all columns in the table to fit widest row including header. */
public static void resizeColumns( JTable table) {
if (table.getGraphics() == null) {
return;
}
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
FontMetrics fm = table.getFontMetrics( renderer.getFont() );
TableColumnModel mod = table.getColumnModel();
for (int iCol = 0; iCol < mod.getColumnCount(); iCol++) {
TableColumn col = mod.getColumn( iCol);
int max = col.getPreferredWidth() - BUF;
String header = table.getModel().getColumnName( iCol);
if (header != null) {
max = Math.max( max, fm.stringWidth( header) );
}
for (int iRow = 0; iRow < table.getModel().getRowCount(); iRow++) {
Object obj = table.getModel().getValueAt(iRow, iCol);
String str = obj == null ? "" : obj.toString();
max = Math.max( max, fm.stringWidth( str) );
}
col.setPreferredWidth( max + BUF);
col.setMaxWidth( MAX);
}
table.revalidate();
table.repaint();
}
/**
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(MouseEvent e) {
if (columnBeingResized == null)
return;
ColumnSettingParameter<CommonColumnType> csPar =
parameters.getParameter(PeakListTableParameters.commonColumns);
ColumnSettingParameter<DataFileColumnType> dfPar =
parameters.getParameter(PeakListTableParameters.dataFileColumns);
final int modelIndex = columnBeingResized.getModelIndex();
final int newWidth = columnBeingResized.getPreferredWidth();
final int numOfCommonColumns = CommonColumnType.values().length;
final int numOfDataFileColumns = DataFileColumnType.values().length;
if (modelIndex < numOfCommonColumns) {
csPar.setColumnWidth(modelIndex, newWidth);
} else {
int dataFileColumnIndex = (modelIndex - numOfCommonColumns) % numOfDataFileColumns;
dfPar.setColumnWidth(dataFileColumnIndex, newWidth);
// set same width to other data file columns of this type
for (int dataFileIndex =
peakList.getNumberOfRawDataFiles() - 1; dataFileIndex >= 0; dataFileIndex--) {
int columnIndex =
numOfCommonColumns + (dataFileIndex * numOfDataFileColumns) + dataFileColumnIndex;
TableColumn col = this.getColumnByModelIndex(columnIndex);
int currentWidth = col.getPreferredWidth();
if (currentWidth != newWidth) {
col.setPreferredWidth(newWidth);
}
}
}
}
/**
* Configure the columns in this model with their preferred size.
*/
private void setDefaultPreferredColumnSizes() {
//
// Unusual Code Alert!
// The table model wants to resize the columns such that they all get an equal share
// of any available width upon initialization. This defeats the preferred size of
// a column if it is specified (which it is usually not). To override this badness,
// we will set all preferred sizes AND then for all columns without a preferred size,
// specify a large value, which causes Java's layout algorithm to have less remaining
// width to divided amongst all the table columns. Essentially, we need to make the
// total width of all columns larger than the table size. We do this by giving large
// default width values.
//
// FYI, Java's badness happens inside of JTable.doLayout().
//
// To easily specify a preferred size for a column, do so in your DynamicTableColumn's
// getColumnPreferredWidth() method. If your model is not dynamic, then you have
// to specify the preferred size manually after you construct your table by grabbing
// its ColumnModel.
//
TableModel model = table.getUnwrappedTableModel();
if (!(model instanceof AbstractGTableModel<?>)) {
return;
}
AbstractGTableModel<?> gModel = (AbstractGTableModel<?>) model;
List<TableColumn> columnList = columnModel.getAllColumns();
for (TableColumn col : columnList) {
int defaultPreferred = col.getPreferredWidth();
if (defaultPreferred > 0 && defaultPreferred != 75) {
// honor any saved preferred size (ignoring the magic default value found
// inside of TableColumn)
col.setWidth(defaultPreferred);
continue;
}
int preferred = gModel.getPreferredColumnWidth(col.getModelIndex());
if (preferred < 15) {
preferred = LARGE_DEFAULT_COL_WIDTH;
}
int size = preferred;
col.setWidth(size);
col.setPreferredWidth(size);
}
}
/**
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
public void mouseReleased(MouseEvent e) {
if (columnBeingResized == null)
return;
ColumnSettingParameter<CommonColumnType> csPar =
parameters.getParameter(PeakListTableParameters.commonColumns);
ColumnSettingParameter<DataFileColumnType> dfPar =
parameters.getParameter(PeakListTableParameters.dataFileColumns);
final int modelIndex = columnBeingResized.getModelIndex();
final int newWidth = columnBeingResized.getPreferredWidth();
final int numOfCommonColumns = CommonColumnType.values().length;
final int numOfDataFileColumns = DataFileColumnType.values().length;
if (modelIndex < numOfCommonColumns) {
csPar.setColumnWidth(modelIndex, newWidth);
} else {
int dataFileColumnIndex = (modelIndex - numOfCommonColumns) % numOfDataFileColumns;
dfPar.setColumnWidth(dataFileColumnIndex, newWidth);
// set same width to other data file columns of this type
for (int dataFileIndex =
peakList.getNumberOfRawDataFiles() - 1; dataFileIndex >= 0; dataFileIndex--) {
int columnIndex =
numOfCommonColumns + (dataFileIndex * numOfDataFileColumns) + dataFileColumnIndex;
TableColumn col = this.getColumnByModelIndex(columnIndex);
int currentWidth = col.getPreferredWidth();
if (currentWidth != newWidth) {
col.setPreferredWidth(newWidth);
}
}
}
}
private void increasePreferredColumnWidth(TableColumn column, int length) {
if (column.getPreferredWidth() < length) {
column.setPreferredWidth(length);
}
}
private static void increasePreferredColumnWidth(TableColumn column, int length) {
if (column.getPreferredWidth() < length) {
column.setPreferredWidth(length);
}
}