【问题标题】:JTable setPreferredWidth() for columns displaying incorrectly列显示不正确的 JTable setPreferredWidth()
【发布时间】:2015-10-26 01:41:13
【问题描述】:

我有一个带有 AbstractTabelModel 的 JTable。我试图在我的项目中创建一个 void 方法,将每列的宽度设置为列中最长值的长度。这是我现在使用的方法,其中“accountWindow”是 JTable:

public void setColumnWidths(){
    accountWindow.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    for (int i = 0; i < accountWindow.getColumnCount(); i++){
        int greatestStringLength = 2;
        for (int z = 0; z < accountWindow.getRowCount(); z++){
            if (accountWindow.getValueAt(z, i).toString().length() > greatestStringLength){
                System.out.println("Width SET");
                greatestStringLength = accountWindow.getValueAt(z, i).toString().length();
                accountWindow.getColumnModel().getColumn(i).setPreferredWidth(greatestStringLength);
            }
            //System.out.println(accountWindow.getValueAt(z, i).toString());
            //System.out.println("Greatest Value: " + greatestValueWidth);
        }
    }
}

在我的 Controller 类 (MVC) 中正确调用了该方法,但它将每列的宽度设置为基本上为 0。在更新表和 fireTableData() 方法之后调用该方法调用并显示帐户信息。我已将 JTable 添加到滚动窗格中。任何 cmets 或建议将不胜感激。

【问题讨论】:

标签: java swing jtable preferredsize


【解决方案1】:

宽度需要以像素为单位,而不是字符串中的字符。

if (accountWindow.getValueAt(z, i).toString().length() > greatestStringLength){

在我看来,您只是获取字符串中的字符数,而不是渲染字符串所需的宽度。也就是说 20 个字符不会以 20 像素呈现。不同的字体,字符串的宽度会有所不同。

查看Table Column Adjuster 了解如何确定渲染宽度的解决方案。它提供了一个简单的用法和一个您可以使用的具有更多功能的自定义类。

这两种解决方案实际上都会调用表格使用的渲染器来确定最大宽度。

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2015-05-30
    • 1970-01-01
    • 2014-09-29
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多