下面列出了javax.swing.JTable#getFontMetrics ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String computeFitText(JTable table, int rowIdx, int columnIdx, String text) {
if(text == null) text = ""; // NOI18N
if (text.length() <= VISIBLE_START_CHARS + 3) return text;
FontMetrics fm = table.getFontMetrics(table.getFont());
int width = table.getCellRect(rowIdx, columnIdx, false).width;
String sufix = "..."; // NOI18N
int sufixLength = fm.stringWidth(sufix + " "); // NOI18N
int desired = width - sufixLength;
if (desired <= 0) return text;
for (int i = 0; i <= text.length() - 1; i++) {
String prefix = text.substring(0, i);
int swidth = fm.stringWidth(prefix);
if (swidth >= desired) {
return prefix.length() > 0 ? prefix + sufix: text;
}
}
return text;
}
private String computeFitText(JTable table, int rowIdx, int columnIdx,
String text) {
if (text == null) {
text = ""; // NOI18N
}
if (text.length() <= 3) {
return text;
}
FontMetrics fm = table.getFontMetrics(table.getFont());
int width = table.getCellRect(rowIdx, columnIdx, false).width;
String prefix = "..."; //NOI18N
int sufixLength = fm.stringWidth(prefix + " "); //NOI18
int desired = width - sufixLength - 15;
if (desired <= 0) {
return text;
}
for (int i = 1; i <= text.length() - 1; i++) {
String part = text.substring(text.length() - i, text.length());
int swidth = fm.stringWidth(part);
if (swidth >= desired) {
return part.length() > 0 ? prefix + part + " " : text; //NOI18N
}
}
return text;
}
public static void configureRowHeight(JTable table) {
int height = table.getRowHeight();
Font cellFont = UIManager.getFont("TextField.font");
if (cellFont != null) {
FontMetrics metrics = table.getFontMetrics(cellFont);
if (metrics != null) {
height = metrics.getHeight() + 2;
}
}
table.setRowHeight(Math.max(table.getRowHeight(), height));
}
/** 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();
}