Java Swing How to - Create JTable without Header








Question

We would like to know how to create JTable without Header.

Answer

//  w  ww .j  av  a  2s .com
import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.UIManager;

public class Main {
    public static void main(String args[]) {
        Object rowData[][] = {
                { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
                { "Row2-Column1", "Row2-Column2", "Row2-Column3" } };
        Object columnNames[] = { "Column 1", "Column 2", "Column 3" };

        JTable table = new JTable(rowData, columnNames);
        table.setTableHeader(null);
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setColumnHeaderView(null);
        JFrame frame = new JFrame();
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    }

    static class HeaderlessTable extends JTable {
        public HeaderlessTable(Object rowData[][], Object columnNames[]) {
            super(rowData, columnNames);
        }

        protected void configureEnclosingScrollPane() {
            Container container = getParent();
            if (container instanceof JViewport) {
                Container viewParent = container.getParent();
                if (viewParent instanceof JScrollPane) {
                    JScrollPane scrollPane = (JScrollPane) viewParent;
                    JViewport viewport = scrollPane.getViewport();
                    if (viewport == null || viewport.getView() != this) {
                        return;
                    }
                    // scrollPane.setColumnHeaderView(getTableHeader());
                    scrollPane.setBorder(UIManager
                            .getBorder("Table.scrollPaneBorder"));
                }
            }
        }
    }
}