对于面板内的 JTable,如果面板变大,我如何才能将额外空间分配给某些列(在我的例子中,分配到最后一列,尽管提供“第 3 列, 4 和 8 将获得额外的空间)。
我想允许用户手动更改所有列的列大小。
我试过 table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); 这会将额外空间分配给所有在调整 JTable 大小时可调整大小的列。在 JTable 的 JavaDoc 中,对于 doLayout(),说:
When the method is called as a result of the resizing of an enclosing window, the resizingColumn is null. This means that resizing has taken place "outside" the JTable and the change - or "delta" - should be distributed to all of the columns regardless of this JTable's automatic resize mode.
可能有一种方法可以拦截“JTable 正在调整大小”事件,并执行一些自定义操作,但我还没有弄明白。
另一种解决方案在 How to exclude columns from auto-resizing in a JTable 虽然它并没有真正告诉我如何在 swing 中做到这一点。
最佳答案
重写doLayout()
方法来拦截布局。这给出了基础知识。当最后一个列宽即将变为负值时,您需要确定要做什么。
import javax.swing.*;
import javax.swing.table.*;
public class Test2Table
{
private static Object[][] data = new Object[][]
{
{ "a", "b", "c" },
{ "d", "e", "f" }
};
private static Object[] colNames = new Object[] { "1", "2", "3" };
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run() {
JTable table = new JTable(data, colNames)
{
@Override
public void doLayout()
{
// Viewport size changed. Change last column width
if (tableHeader != null
&& tableHeader.getResizingColumn() == null)
{
TableColumnModel tcm = getColumnModel();
int delta = getParent().getWidth() - tcm.getTotalColumnWidth();
TableColumn last = tcm.getColumn(tcm.getColumnCount() - 1);
last.setPreferredWidth(last.getPreferredWidth() + delta);
last.setWidth(last.getPreferredWidth());
}
else
{
super.doLayout();
}
}
};
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
});
}
}
关于java - 当容器大小更改时,JTable 仅调整选定列的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368343/