Here you can find the source of adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table)
Parameter | Description |
---|---|
model | a parameter |
columnIndex | a parameter |
table | a parameter |
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table)
//package com.java2s; /*/* w ww .jav a 2 s.c o m*/ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import javax.swing.*; import javax.swing.table.TableModel; import java.awt.*; public class Main { /** * It will adjust the column width to match the widest element. * (You might not want to use this for every column, consider some columns might be really long) * @param model * @param columnIndex * @param table * @return */ public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table) { if (columnIndex > model.getColumnCount() - 1) { //invalid column index return; } if (!model.getColumnClass(columnIndex).equals(String.class)) { return; } String longestValue = ""; for (int row = 0; row < model.getRowCount(); row++) { String strValue = (String) model.getValueAt(row, columnIndex); if (strValue != null && strValue.length() > longestValue.length()) { longestValue = strValue; } } Graphics g = table.getGraphics(); try { int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g) .getWidth(); table.getColumnModel().getColumn(columnIndex) .setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth) + rightPadding); } catch (Exception e) { table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth); e.printStackTrace(); } } }