java中jtable的宽度_java-如何获取正确的JTable宽度?

我想要一张桌子的宽度.我尝试使用以下代码进行操作:

private static class ListenerForOk implements ActionListener {

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

handle();

if (!dataIsNotInput()) {

createDataTab();

System.out.println(table.getWidth());

}

}

方法createDataTab()完成添加JTable的所有工作.因此,在createDataTab();之后;我的桌子放在框架上,我可以看到它.但是这段代码table.getWidth()返回零.我尝试使用此代码获取表宽度的另一种方法:

double sum = 0.0;

for (int i = 0; i < table.getColumnCount(); i++) {

sum += table.getColumnModel().getColumn(i).getWidth();

}

System.out.println("sum: " + sum);

table.getColumnModel().getColumn(i).getWidth()方法为所有列返回75.这是正确的值,并且我的表宽度正确.但是在我的表类中,我重写了一种方法.这是我的代码:

class MyTable extends JTable {

@Override

public Component prepareRenderer(TableCellRenderer renderer, int row,

int column) {

Component component = super.prepareRenderer(renderer, row, column);

int rendererWidth = component.getPreferredSize().width;

TableColumn tableColumn = getColumnModel().getColumn(column);

tableColumn

.setPreferredWidth(Math.max(rendererWidth

+ getIntercellSpacing().width,

tableColumn.getPreferredWidth()));

return component;

}

因此,如果我在任何列中输入长字符串,则该列将相应地扩展为带有文本的地方.我做到了,专栏扩大了.但是在那之后方法table.getColumnModel().getColumn(i).getWidth();再次为所有列返回75.因此,如何获得正确的表格宽度.

解决方法:

调整列宽的基本代码是:

JTable table = new JTable( ... );

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

for (int column = 0; column < table.getColumnCount(); column++)

{

TableColumn tableColumn = table.getColumnModel().getColumn(column);

int preferredWidth = tableColumn.getMinWidth();

int maxWidth = tableColumn.getMaxWidth();

for (int row = 0; row < table.getRowCount(); row++)

{

TableCellRenderer cellRenderer = table.getCellRenderer(row, column);

Component c = table.prepareRenderer(cellRenderer, row, column);

int width = c.getPreferredSize().width + table.getIntercellSpacing().width;

preferredWidth = Math.max(preferredWidth, width);

// We've exceeded the maximum width, no need to check other rows

if (preferredWidth >= maxWidth)

{

preferredWidth = maxWidth;

break;

}

}

tableColumn.setPreferredWidth( preferredWidth );

}

您也可以检出Table Column Adjuster,以获取包含上述代码并添加诸如更改数据时的自动列调整之类的附加功能的类.

标签:java,swing,jtable

来源: https://codeday.me/bug/20191011/1892159.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值