关于JTable不能显示表头的问题(个人小结)

来源:互联网 发布:力港网络笔试题 编辑:程序博客网 时间:2024/06/05 07:39

好久不写了,最近又联系熟悉起了Swing的东西,遇到问题:

 

JTable 不能正确显示标题,关于这个,官方文档里面有说:

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 scrolls 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);在使用时要注意!

 

所以说使用JTable显示数据时,要将Table添加在JScrollPane里面;

 

但是我的代码里面还是显示不出来,开始检查原因:

原来:如下添加table不行:

scrollPanel.add(table);

应该改为:

scrollPanel.setViewportView(table);//解决显示表头问题:必须用这个

但是,这样似乎还是不行,在检查,在尝试,终于:

将scrollPane的setLayout(null);注释掉,再试,Ok;

 

&&&&&&&&&&&&&&&&&&&&&&&&&&&&

这里,针对我的问题总结三点::

 

1、用JScrollPane承接Table,不用JPanel等;

2、用JScrollPane的构造函数构建,或者用scrollPanel.setViewportView(table);

   不用scrollPanel.add(table);

3、承接Table的父容器的布局管理器不能设置为null,其实,对于JScrollPane的布局,有专门的

   scroll的布局,也可以用,简便的话,不设置布局;不要Null;

至此,Table和表头都可以正常显示了。

 

问题比较个体化,有用的可以参考,有好方法希望提意见;

原创粉丝点击