简体   繁体   English

调整列宽以动态适应 JTable 中 JScrollPane 内的内容

[英]Resize columns width to fit content dynamically of JTable that it's inside of a JScrollPane

I'm currently using this code (taken from here ) to resize columns width, which is working, the table cells are not editable, the content is added dynamically using a DefaultTableModel, but if a row width is greater than the table, it doesn't use the scroll panel.我目前正在使用此代码(取自此处)来调整列宽,这是有效的,表格单元格不可编辑,使用 DefaultTableModel 动态添加内容,但如果行宽大于表格,则不会不要使用滚动面板。

This is my table definition这是我的表定义

JScrollPane jScrollPane1 = new JScrollPane();
JTable jTable = new JTable();

jTable.setModel(new DefaultTableModel(
   new Object [][] {
   },
         
   new String [] {
      "COLUMN1", "COLUMN2"
   }) {
      Class[] types = new Class [] {
         String.class, String.class
      };

      boolean[] canEdit = new boolean [] {
         false, false
      };

      public Class getColumnClass(int columnIndex) {
         return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
         return canEdit [columnIndex];
      }
});

TableColumnAdjuster tblAdjuster = new TableColumnAdjuster(jTable);
tblAdjuster.setDynamicAdjustment(true);

jScrollPane1.setViewportView(jTable);

Are they any suggestions?他们有什么建议吗?

I already solved it by following the rule defined by the developer of the code I used:我已经按照我使用的代码的开发人员定义的规则解决了它:

Note, that this class was designed to be used with tables that use an auto resize mode of AUTO_RESIZE_OFF.请注意,此类旨在与使用 AUTO_RESIZE_OFF 的自动调整大小模式的表一起使用。 With all other modes you are constrained, as the width of the columns must fit inside the table.对于所有其他模式,您都受到限制,因为列的宽度必须适合表格内。 So if you increase the width of one column, the widths of one or more of the other columns must decrease.因此,如果您增加一列的宽度,则其他一列或多列的宽度必须减小。 Because of this, the resize mode of RESIZE_ALL_COLUMNS will work the best.因此,RESIZE_ALL_COLUMNS 的调整大小模式将发挥最佳效果。

So I have to set the AutoResizeMode to OFF before the creation of the TableColumnAdjuster instance:所以我必须在创建 TableColumnAdjuster 实例之前将 AutoResizeMode 设置为 OFF:

jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

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

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