[英]How to individually set the width of a row on a table/scrollpane
我有一个 DefaultTableModel:
DefaultTableModel model = new DefaultTableModel(data, beschriftung)
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
这是在一张桌子里面:
JTable table = new JTable(model);
table.setEnabled(false);
table.setRowHeight(50);
该表位于 scrollPane 内:
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(1215, 11, 300, 300);
scrollPane.setWheelScrollingEnabled(true);
scrollPane.setEnabled(false);
getContentPane().add(scrollPane);
我有两行,但希望第一行比第二行短。 有什么建议么?
这是它的样子:
这就是我希望它的样子:
查看:
基本代码是:
table.getColumnModel().getColumn(???).setPreferredWidth(???)
这种方法的基本代码是:
JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < table.getColumnCount(); column++)
{
TableColumn tableColumn = table.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = tableColumn.getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
{
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth( preferredWidth );
}
链接中的TableColumnAdjuster
class 还包含其他功能。
另请查看 JTable API 的setAutoResizeMode(...)
方法,以确定在表格宽度发生变化时如何分配空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.