Java - 根据列调整大小调整 table

Java - Resize the table based on the column resizing

我有一个包含 2 列的 JTable,我试图实现以下目标:
如果第一列中某个单元格的值不适合该单元格,那么您会看到 3 个结束点。在这种情况下,我想调整列以及 table 的大小,以便长值适合,以免更改第二列的宽度。将其视为左侧第一列的扩展。

示例代码:

/**
 * Main.
 * 
 * @param args arguments.
 */
public static void main(String[] args) {
  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  JPanel panel = new JPanel(new GridBagLayout());

  String[] columnNames = {"First Name",
    "Last Name"};
  Object[][] data = {
    {"Kathy Lathy Alberta 1234567890 11 12 13 14", "Smith"},
    {"John", "Doe"},
    {"Sue", "Black"},
    {"Jane", "White"},
    {"Joe", "Brown"}
  };


  // Create the table based on data and column names
  JTable table = new JTable(new DefaultTableModel(data, columnNames));
  // Set an initial size and add it to the main panel
  table.setSize(300, 300);
  panel.add(table);

  // Compute the width of the first column, based on the longest value
  int width = 0, row = 0;
  for (row = 0; row < table.getRowCount(); row++) {
      TableCellRenderer renderer = table.getCellRenderer(row, 0);
      Component comp = table.prepareRenderer(renderer, row, 0);
      width = Math.max (comp.getPreferredSize().width, width);
  }

  // Compute the value to be added to the width of the table
  int initialWidth = table.getColumnModel().getColumn(0).getPreferredWidth();
  int delta = width - initialWidth;
  // Try to resize the table and the first column
  table.setPreferredSize(new Dimension(table.getPreferredSize().width + delta, table.getHeight()));
  table.getColumnModel().getColumn(0).setPreferredWidth(width);

  frame.getContentPane().add(panel);
  panel.setLayout(new BorderLayout());
  panel.setPreferredSize(table.getPreferredSize());
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  frame.pack();
  frame.setLocation(800, 300);
  frame.setVisible(true);
}

这是怎么回事:

几个问题:

您两次设置面板的布局管理器,第一次是 GridBagLayout,然后是 BorderLayout。布局管理器应在开始向面板添加组件之前设置一次。

width = Math.max (comp.getPreferredSize().width, width);

首选宽度将太小,因为 table 还包括列宽中的单元格间距量。对于简单的解决方案,您可以使用:

width = Math.max (comp.getPreferredSize().width + 1, width);

您可以查看 Table Column Adjuster 以了解我用来调整列宽的更通用的代码。

// Compute the value to be added to the width of the table
//  int initialWidth = table.getColumnModel().getColumn(0).getPreferredWidth();
//  int delta = width - initialWidth;
// Try to resize the table and the first column
//  table.setPreferredSize(new Dimension(table.getPreferredSize().width + delta, table.getHeight()));
table.getColumnModel().getColumn(0).setPreferredWidth(width);

不要尝试使用 table 的首选宽度。只需设置 TableColumn 的宽度并让 table 计算它自己的宽度。