简体   繁体   English

添加JScrollPane后JTable不显示

[英]JTable doesn't show after adding JScrollPane

This is my code : 这是我的代码:

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);

It worked fine until I added JScrollPane. 在添加JScrollPane之前,它工作正常。 Now it is blank. 现在是空白。 What am I doing wrong here ? 我在这里做错了什么? Let me know if you need anything else. 需要帮助请叫我。

As @HovercraftFullOfEels wisely points out the call to Component.setBounds() mess the things up: 正如@HovercraftFullOfEels明智地指出,对Component.setBounds()的调用将事情搞砸了:

public void setBounds(int x, int y, int width, int 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 . 左上角的新位置由xy指定,新大小由widthheight指定。

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. 通常,您永远不要调用此方法,而应使用适当的LayoutManager来管理组件的大小和位置。 Take a look to Using Layout Managers and A Visual Guide to Layout Managers for further information. 有关更多信息,请参见 使用布局管理器可视化指南

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? 如果需要为表提供默认大小,则可以考虑使用JTable.setPreferredScrollableViewportSize()方法,但请始终牢记以下主题: 我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法?

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 . 因为框架的内容窗格已经具有默认的布局管理器: BorderLayout And finally don't forget to call frame.pack() method. 最后不要忘了调用frame.pack()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM