简体   繁体   English

Jtable保留列宽

[英]Jtable retain column width

我有一个Jtable,我在其中使用setDataVector函数设置数据。它工作正常,但假设如果我只是通过使用鼠标拖动来更改了某些列宽,并且在同一表中加载了新数据之后,该列的宽度将重置到它的默认位置。所以基本上我想保留该宽度,即使加载新数据也是如此。

When you use the setDataVector() method the structure of the table may change so the table automatically recreates the TableColumnModel and you lose your customization. 当您使用setDataVector()方法时,表的结构可能会更改,因此该表会自动重新创建TableColumnModel,并且您将丢失自定义设置。

When you create the JTable the first time use code like: 首次创建JTable时,请使用如下代码:

JTable table = new JTable(...);
table.setAutoCreateColumnsFromModel( false );

to prevent the TableColumnModel from being recreated. 以防止重新创建TableColumnModel。

That happens because when you use setDataVector() according to docs that recreates columns and your column width changes to default. 发生这种情况是因为当您根据文档使用setDataVector()来重新创建列并且列宽更改为默认值时。

Try to use setAutoCreateColumnsFromModel() to prevent that behavior. 尝试使用setAutoCreateColumnsFromModel()来防止该行为。

As you use a custom table model. 当您使用自定义表模型时。 Don't use setDateVector() it recreates the columns. 不要使用setDateVector()来重新创建列。 You can manage width of column using setPreferredWidth() method manually as: 您可以使用setPreferredWidth()方法手动管理列宽,如下所示:

      table.setModel(buildTableModel(rs));
      TableColumnModel tcm = table.getColumnModel();
      tcm.getColumn(0).setPreferredWidth(80);  
      tcm.getColumn(1).setPreferredWidth(200);  
      tcm.getColumn(2).setPreferredWidth(100);  
      tcm.getColumn(3).setPreferredWidth(100);  
      tcm.getColumn(4).setPreferredWidth(100);  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM