关于JTable不能显示表头的问题

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和表头都可以正常显示了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值