Java JTable Column headers not showing

情到浓时终转凉″ 提交于 2019-11-29 14:39:29
Amarnath

Here is the problem.

JTable table = new JTable (data, columnNames);
f.add(table);

Do not add the table directly. Use JScrollPane to show the table headers.

f.add(new JScrollPane(table))

Why do you need to put the table in the JScrollPane?

From @Dan post:

When you put the component inside the constructor of a JScrollPane, you mention which is the view to which the scroll to be applied for.

On the other side, using the add method, you just add a component to a container, like adding it to a JPanel. This way, you don't specify the component to add the scroll bars to.

EDIT: From javadoc (cited by trashgod in the comment section)

Here is typical code for creating a scroll pane that serves as a container for a table:

JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true); 

The two lines in this snippet do the following: The JScrollPane constructor is invoked with an argument that refers to the table object. This creates a scroll pane as a container for the table; the table is automatically added to the container. JTable.setFillsViewportHeight is invoked to set the fillsViewportHeight property. When this property is true the table uses the entire height of the container, even if the table doesn't have enough rows to use the whole vertical space. This makes it easier to use the table as a drag-and-drop target. The scroll pane automatically places the table header at the top of the viewport. The column names remain visible at the top of the viewing area when the table data is scrolled.

If you are using a table without a scroll pane, then you must get the table header component and place it yourself. For example:

container.setLayout(new BorderLayout());
container.add(table.getTableHeader(), BorderLayout.PAGE_START);
container.add(table, BorderLayout.CENTER);

If I remember correctly, you should put a container (e.g. a JScrollPane) around it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!