要么这不存在,要么我没有正确思考/搜索,因为它已经晚了......
我想根据我期望(或知道)存在于特定列中的最大字符串的原型值在 Swing 中设置 JTable 列宽。我不知道像素数,因为我在编译时不一定知道字体。
有没有办法为列宽设置原型值,就像行高一样?如果是这样,怎么做?
要么这不存在,要么我没有正确思考/搜索,因为它已经晚了......
我想根据我期望(或知道)存在于特定列中的最大字符串的原型值在 Swing 中设置 JTable 列宽。我不知道像素数,因为我在编译时不一定知道字体。
有没有办法为列宽设置原型值,就像行高一样?如果是这样,怎么做?
您可以尝试以下代码:
/**
* Sets the preferred width of the columns of a table from prototypes
* @param table the target table
* @param prototypes an array of prototypes, {@code null} values will be ignored
* @param setMaxWidth {@code true} if the maximum column width should also be set
*/
public static void setWidthFromPrototype(JTable table, Object[] prototypes, boolean setMaxWidth) {
if (prototypes.length != table.getColumnCount())
throw new IllegalArgumentException("The prototypes array should contain exactly one element per table column");
for (int i = 0; i < prototypes.length; i++) {
if (prototypes[i] != null) {
Component proto = table.getCellRenderer(0,i)
.getTableCellRendererComponent(table, prototypes[i], false, false, 0, i);
int prefWidth = (int) proto.getPreferredSize().getWidth() + 1;
table.getColumnModel().getColumn(i).setPreferredWidth(prefWidth);
if (setMaxWidth)
table.getColumnModel().getColumn(i).setMaxWidth(prefWidth);
}
}
}
您是否尝试过在运行时创建 JLabel 并使用它的大小来调整表格的大小?
// create a label that will be using the run-time font
JLabel prototypeLabel = new JLabel("Not Applicable")
// get the labels preferred sizes
int preferredWidth = prototypeLabel.getPreferredSize().getWidth();
int preferredHeight = prototypeLabel.getPreferredSize().getHeight();
// set the sizes of the table's row and columns
myTable.setRowHeight(preferredHeight);
for(TableColumn column : myTable.getColumnModel.getColumns()){
column.setPreferredWidth(preferredWidth);
}
SwingX扩展的 JXTable/Column 支持为初始列宽大小设置原型,您可以在创建列之后执行此操作
for(int col = 0; ....) {
table.getColumnExt(col).setPrototypeValue(myPrototype[col]
}
或者通过实现一个自定义 ColumnFactory 来配置创建时的列
ColumnFactory factory = new ColumnFactory() {
@Override
protected void configureTableColumn(TableModel model, TableColumnExt columnExt) {
super(...);
columnExt.setPrototypeValue(myPrototype[columnExt.getModelIndex()];
}
}
table.setColumnFactory(factory);
table.setModel(myModel);
不要创建标签,而是从 TableCellRenderer 获取实际组件并测试其大小:
// create the component that will be used to render the cell
Comp prototype = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, "Not Applicable", false, false, 0, i);
// get the labels preferred sizes
int preferredWidth = comp.getPreferredSize().getWidth();
int preferredHeight = comp.getPreferredSize().getHeight();
这是一个单列示例,您需要重复此操作以获取每列的大小(并设置它)。有关此示例,请参见http://www.exampledepot.com/egs/javax.swing.table/PackCol.html 。
如果您在编译时不知道字体,那么任何 JTable 列的宽度总是未知的。作为健全性检查,打开一个文本文档并使用不同的字体,同时保持点大小不变。所写内容的长度因字体而异,但高度不会。
JTable 行的高度应该能够针对任何字体大小(以磅为单位)确定,因为它是定义的标准。不过,考虑到 JTable 可能会在单元格之间留出一点间距,这可能需要进行一些试验。
如果您在编译时不能保证字体大小和字体本身,那么我对其他人提出的答案很感兴趣:)