繁体   English   中英

如何单独设置表格/滚动窗格上的行宽

[英]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);

我有两行,但希望第一行比第二行短。 有什么建议么?

这是它的样子:

https://i.stack.imgur.com/XQQsz.png

这就是我希望它的样子:

https://i.stack.imgur.com/28UTf.png

查看:

  1. 检查 Swing 教程中关于设置和更改列宽的部分。 它显示了如何手动为每列设置首选大小。

基本代码是:

table.getColumnModel().getColumn(???).setPreferredWidth(???)
  1. 您还可以查看表格列调整器,以根据 model 中包含的数据自动调整列大小

这种方法的基本代码是:

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.

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