添加JScrollPane后JTable不显示 [英] JTable doesn't show after adding JScrollPane

查看:225
本文介绍了添加JScrollPane后JTable不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

table = new JTable(tableModel);
final TableRowSorter<TableModel> sorter = new TableRowSorter(tableModel);
table.setRowSorter(sorter);
table.setBounds(122, 47, 162, 204);

JScrollPane scroller = new JScrollPane(table);
frame.getContentPane().add(scroller);

在我添加JScrollPane之前,它运行良好.现在是空白.我在这里做错了什么?让我知道您是否还有其他需要.

It worked fine until I added JScrollPane. Now it is blank. What am I doing wrong here ? Let me know if you need anything else.

推荐答案

@HovercraftFullOfEels明智地指出了对

As @HovercraftFullOfEels wisely points out the call to Component.setBounds() mess the things up:

public void setBounds(int x, int y, int width, int height)

移动此组件并调整其大小.左上角的新位置 角由xy指定,新大小由width指定 和height.

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height.

此方法更改与布局有关的信息,因此, 使组件层次结构无效.

This method changes layout-related information, and therefore, invalidates the component hierarchy.

通常,您永远不应调用此方法,而应使用正确的使用布局管理器布局管理器的可视指南,以获取更多信息.

Generally you should never call this method and should use a proper LayoutManager instead which is intended to manage components size and positioning. Take a look to Using Layout Managers and A Visual Guide to Layout Managers for further information.

如果需要为表提供默认大小,则可以考虑使用我应该避免使用set(Preferred | Maximum | Minimum)Size方法吗?

If you need to provide a default size to your table then you may consider use JTable.setPreferredScrollableViewportSize() method, but always keep in mind this topic: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

特别是在这种情况下,如果您的框架仅包含滚动窗格,则此顺序应足够:

Particularly in this case if your frame will only contain the scroll pane then this sequence should be enough:

JScrollPane scroller = new JScrollPane(table);
frame.getContentPane().add(scroller);
frame.pack();

因为框架的内容窗格已具有默认的布局管理器:

Because the frame's content pane has already a default layout manager: BorderLayout. And finally don't forget to call frame.pack() method.

这篇关于添加JScrollPane后JTable不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆