我有一个包含许多列的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 (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; }
}发布于 2011-10-16 05:54:22
包括:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);发布于 2015-03-25 18:02:14
尽管我尝试了另外两个答案,但我也遇到了类似的问题。在我的例子中,有时宽度会被正确设置,而另一些时候则不会。我发现问题是造成的,因为我试图在更改表模型后立即设置列宽。我发现在SwingUtilities.invokeLater()中设置列宽是很有效的。也就是。
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
int width = 100;
for (int column = 1; column < table.getColumnCount(); column++) {
columnModel.getColumn(column).setPreferredWidth(width);
}
}
}发布于 2014-08-29 08:48:08
我知道这有点晚了,对未来的读者来说也是如此,但我也遇到了同样的问题,并通过将专栏的首选宽度和最大宽度设置为相同的值来解决这个问题。
https://stackoverflow.com/questions/7782609
复制相似问题