【问题标题】:Java - Resize the table based on the column resizingJava - 根据列大小调整表大小
【发布时间】:2015-12-31 09:59:13
【问题描述】:

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

示例代码:

/**
 * 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);
}

会发生什么:

【问题讨论】:

标签: java swing jtable


【解决方案1】:

几个问题:

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

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

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

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);

不要尝试使用首选的桌子宽度。只需设置 TableColumn 的宽度,让表格自己计算宽度即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2016-06-18
    • 2017-01-19
    相关资源
    最近更新 更多