调整 Jtable 列宽度不起作用

发布于 2024-07-15 06:12:14 字数 781 浏览 7 评论 0原文

//can set column widths using percentages   
private void setPreferredTableColumnWidths(JTable table, double[] percentages) 
{
    Dimension tableDim = table.getSize(); 

    double total = 0; 
    for(int i = 0; i < table.getColumnModel().getColumnCount(); i++) 
      total += percentages[i]; 

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    for(int i = 0; i < table.getColumnModel().getColumnCount(); i++) 
    { 
      TableColumn column = table.getColumnModel().getColumn(i); 
      column.setPreferredWidth((int) (tableDim.width * (percentages[i] / total)));
    }
}

我希望能够根据表总宽度的百分比更改 JTable 的宽度。 上面的代码看起来应该可以工作,但是当我使用“setPreferredTableColumnWidths(table, new double[] {.01,.4,.2,.2,.2});”调用它时,我只能得到等宽的列。

可能是什么问题呢?

//can set column widths using percentages   
private void setPreferredTableColumnWidths(JTable table, double[] percentages) 
{
    Dimension tableDim = table.getSize(); 

    double total = 0; 
    for(int i = 0; i < table.getColumnModel().getColumnCount(); i++) 
      total += percentages[i]; 

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    for(int i = 0; i < table.getColumnModel().getColumnCount(); i++) 
    { 
      TableColumn column = table.getColumnModel().getColumn(i); 
      column.setPreferredWidth((int) (tableDim.width * (percentages[i] / total)));
    }
}

I want to be able to change the widths of a JTable based on a percentage of the total width of the table. The above code looks like it should work, but I only get equal width columns when I call it using "setPreferredTableColumnWidths(table, new double[] {.01,.4,.2,.2,.2});"

What could be the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的他你的她 2024-07-22 06:12:14

尝试添加行:

table.doLayout();

在该方法的最后。

Try to add the line:

table.doLayout();

At the end of the method.

似梦非梦 2024-07-22 06:12:14

您的代码工作正常,但根据您调用它的位置,表格可能有也可能没有宽度。 在面板(或包含表格的任何内容)的构造函数中,还没有宽度。

我将对您的方法的调用放在 Paint() 方法中。 但请务必跟踪并只调用一次,否则它会一遍又一遍地调整列的大小。

@Override
public void paint(Graphics g) {
    super.paint(g);

    if(! this.initialSizeSet){
        this.setPreferredTableColumnWidths(this.table, new double[] {0.1, 0.1, 0.5, 0.3});
        this.initialSizeSet = true;
    }
}

Your code works fine but depending on where you call it the table may or may not have a width. In the constructor of a Panel (or whatever contains the table) there is not width yet.

I put the call to your method in the paint() method. But be sure to keep track and only call it once or it will resize the columns over and over.

@Override
public void paint(Graphics g) {
    super.paint(g);

    if(! this.initialSizeSet){
        this.setPreferredTableColumnWidths(this.table, new double[] {0.1, 0.1, 0.5, 0.3});
        this.initialSizeSet = true;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文