我有一个JTable,其中包含多列。我想要调整特定的一列大小。我希望使用setPreferredWidth方法,该列会调整到指定的大小,或者根据内容自动调整大小,而不会发生截断,让其余的列占据剩余的空间。但是实际上,所有的列(包括我调整大小的那一列)平均分配了表格的所有空间;就好像setPreferredWidth什么也没做一样。实际上,我想要设置列的宽度,并使其缩小到指定的大小,而不截断内容(我强调得够多了吗?),并且未调整大小的所有列填充剩余空间。使用setMaxWidth会截断内容(我提到我不喜欢这个了吗?)。如何调整/缩小列而不截断内容,同时又不会完全无效?以下是有问题的代码:
for (int i = 0, x = 0; i < table.getColumnModel().getColumnCount(); i++)
if ((x = model.getColumnWidth(i)) > -1)
table.getColumnModel().getColumn(i).setPreferredWidth(x);
这张表格位于一个JPanel中(MyListPanel - BorderLayout),该JPanel又位于另一个JPanel中(GridBagLayout)。添加方式为:
new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 0, 2), 0, 0))
编辑:这是我JPanel子类的构造函数:
public MyListPanel(boolean showHeader, String title, ColData...columns) {
super(new BorderLayout());
model = new MyListTableModel(columns);
table = new JTable(model);
table.addFocusListener(this);
add(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
setTitle(title);
if (showHeader)
add(table.getTableHeader(), BorderLayout.NORTH);
for (int i = 0, x = 0; i < table.getColumnModel().getColumnCount(); i++)
if ((x = model.getColumnWidth(i)) > -1)
table.getColumnModel().getColumn(i).setPreferredWidth(x);
setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
}
而 MyListTableModel.ColData:
public static class ColData {
private int index;
private String title;
private int width;
public ColData(int _index, String _title, int _width) { index = _index; title = _title; width = _width; }
}