gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:04:07 24 4
gpt4 key购买 nike

我有一个包含 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);
}

发生的事情是这样的:

enter image description here

最佳答案

几个问题:

您将面板的布局管理器设置两次,第一次设置为 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的宽度并让表格计算自己的宽度即可。

关于Java - 根据列大小调整表大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34544595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com