JScrollPane中添加JTable不能显示表头

JScrollPane中添加JTable不能显示表头,第1张

JTable组件显示数据时,如果直接将其放置在Frame的contentPane中则表头一行会显示不出来,如果将其放置在JScrollPane中显示数据的话,表头会自动显示出来。

引用Sun的原话为:

It's easy to put a table in a scroll pane. You need just one or two lines of code:

JScrollPane scrollPane = new JScrollPane(table)

table.setPreferredScrollableViewportSize(new Dimension(500, 70))

The scroll pane automatically gets the table's header, which displays the column names, and puts it on top of the table. Even when the user scroll户孩膏绞薇悸疙溪躬娄s down, the column names remain visible at the top of the viewing area. The scroll pane also tries to make its viewing area the same as the table's preferred viewing size. The previous code snippet sets the table's preferred viewing size with the setPreferredScrollableViewportSize method.

If you're 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)在使用时要注意!

你可以先用一个JPanel,选择一种布局方式FlowLayout或者BorderLayout.向此JPanle中按布局添加

多个JTable,然后再将此JPanel添加到JScrollPanel中即可.

给窗口添加resize事件,当窗口大小改变的时候重设table的行高即可。

比如window中用borderlayout放置一panel,panel中放table,那么这个panel增加java.awt.event.ComponentListener这个事件就可以随jframe大小变化。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11751845.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存