java jtable设置列宽_java - Java JTable设置列宽 - 堆栈内存溢出

阅读Kleopatra的话(她第二次建议看一看javax.swing.JXTable ,现在对不起,我第一次没看一看:))我建议您点击链接

对于相同的问题,我有以下解决方案:(但建议您点击上面的链接)在调整表大小时,将表列的宽度缩放到当前表的总宽度。 为此,我将整数数组用于(相对)列宽):

private int[] columnWidths=null;

我使用此功能来设置表格的列宽:

public void setColumnWidths(int[] widths){

int nrCols=table.getModel().getColumnCount();

if(nrCols==0||widths==null){

return;

}

this.columnWidths=widths.clone();

//current width of the table:

int totalWidth=table.getWidth();

int totalWidthRequested=0;

int nrRequestedWidths=columnWidths.length;

int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);

for(int col=0;col

int width = 0;

if(columnWidths.length>col){

width=columnWidths[col];

}

totalWidthRequested+=width;

}

//Note: for the not defined columns: use the defaultWidth

if(nrRequestedWidths

log.fine("Setting column widths: nr of columns do not match column widths requested");

totalWidthRequested+=((nrCols-nrRequestedWidths)*defaultWidth);

}

//calculate the scale for the column width

double factor=(double)totalWidth/(double)totalWidthRequested;

for(int col=0;col

int width = defaultWidth;

if(columnWidths.length>col){

//scale the requested width to the current table width

width=(int)Math.floor(factor*(double)columnWidths[col]);

}

table.getColumnModel().getColumn(col).setPreferredWidth(width);

table.getColumnModel().getColumn(col).setWidth(width);

}

}

设置数据时,我称:

setColumnWidths(this.columnWidths);

并更改后,将ComponentListener设置为表的父级(在我的情况下为JScrollPane,它是表的容器):

public void componentResized(ComponentEvent componentEvent) {

this.setColumnWidths(this.columnWidths);

}

请注意,JTable表也是全局的:

private JTable table;

在这里,我设置了侦听器:

scrollPane=new JScrollPane(table);

scrollPane.addComponentListener(this);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值