如何使 JTable 既可以自动调整大小又可以水平滚动?
我将 JTable 放入 JScrollPane
但是当我设置 JTable 自动调整大小时,它不会有水平滚动条。
如果我设置 AUTO_RESIZE_OFF,那么当列宽不够大时,Jtable 将不会填充其容器的宽度。
那么我该如何做到这一点:
- 当表格不够宽时,展开以填充其容器宽度
- 当表格足够宽时,使其可滚动。
谢谢
I am putting a JTable into a JScrollPane
But When I set JTable Auto Resizeable, then it won't have horizontal scroll bar.
if I set AUTO_RESIZE_OFF, then the Jtable won't fill the width of its container when the column width is not big enough.
So how can I do this:
- when the table is not wide enough, expand to fill its container width
- when the table is wide enough, make it scrollable.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要自定义 Scrollable 界面的行为。
上面的代码基本上按照其首选大小或视口大小(以较大者为准)调整组件的大小。
You need to customize the behaviour of the Scrollable interface.
The above code basically sizes the component at its preferred size or the viewport size, whichever is greater.
如果由于某种原因无法选择自定义 JTable(例如,它可能是在第三方代码中创建的),则可以通过将其设置为在调整包含的视口大小时在两种不同的 JTable AUTO_RESIZE 模式之间切换来实现相同的结果,例如:
If for some reason customising JTable is not an option (e.g. it might be created in third-party code), you can achieve the same result by setting it to toggle between two different JTable AUTO_RESIZE modes whenever the containing viewport is resized, e.g.:
我发现所需要的只是包含
,然后当计算出所需的视口宽度和高度时,包含
I found that all that is needed is to include
and then when the required viewport width and height have been calculated, include
如果将其容器的布局设置为 BorderLayout 使用 BorderLayout.CENTER 布局约束,那么JTable 将自动调整大小以适合其容器。
如果要使组件可滚动,可以使用 JScrollPane。
If you set the Layout of its container to BorderLayout with a BorderLayout.CENTER layout constraint, then the JTable will auto resize to fit its container.
If you want to make a component scrollable, you can wrap the JTable with a JScrollPane.