JTable doesn't show after adding JScrollPane

萝らか妹 提交于 2019-12-13 06:14:52

问题


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. Now it is blank. What am I doing wrong here ? Let me know if you need anything else.


回答1:


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)

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.

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.



来源:https://stackoverflow.com/questions/20911857/jtable-doesnt-show-after-adding-jscrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!