开发者

how to build a custom JTable in Java, with a row above the column names

开发者 https://www.devze.com 2023-03-21 06:17 出处:网络
I am usingAbstractTableModel to create a simple custom table,as usual with a String[] for the col开发者_JAVA技巧umn names and Object[][] for the contents in the JTable\'s rows .But, I found it hard to

I am using AbstractTableModel to create a simple custom table,as usual with a String[] for the col开发者_JAVA技巧umn names and Object[][] for the contents in the JTable's rows .But, I found it hard to create a table containing an additional row (of one big cell spanning all columns for a general title) before the column names. Does anyone have any idea?


by using BorderLayout you can place TableHeader to the bottom of the Container

add(table, BorderLayout.CENTER);
add(header, BorderLayout.SOUTH);


It depends what you want your general title to look like.

You can easily add a JLabel above the table in a separate panel. Something like:

JPanel tablePanel = new JPanel( new BorderLayout() );
JLabel label = new JLabel( "Table Title" );
label.setHorizontalAlignment( JLabel.CENTER );
tablePanel.add(label, BorderLayout.NORTH);
JTable table = new JTable(...);
JScrollPane scrollPane = new JScrollPane( table );
tablePanel.add(scrollPane, BorderLayout.CENTER);

If you want the title to actually be a part of the column header then it is a little trickier. One way to do this is something like:

JTable table = new JTable(...)
{
    @Override
    protected void configureEnclosingScrollPane()
    {
        super.configureEnclosingScrollPane();

        Container parent = getParent();

        if (parent instanceof JViewport)
        {
            parent = parent.getParent();

            if (parent instanceof JScrollPane)
            {
                JScrollPane scrollPane = (JScrollPane)parent;

                JPanel columnHeader = new JPanel( new BorderLayout() );
                JLabel label = new JLabel( "Table Title" );
                label.setHorizontalAlignment( JLabel.CENTER );
                columnHeader.add(label, BorderLayout.NORTH);
                columnHeader.add(getTableHeader(), BorderLayout.CENTER);
                scrollPane.setColumnHeaderView( columnHeader );
            }
        }
    }
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
0

精彩评论

暂无评论...
验证码 换一张
取 消