0

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Marijus
  • 4,195
  • 15
  • 52
  • 87

1 Answers1

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.

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
  • Using layout manager means I have to rewrite my whole GUI. Is there any way around this ? Perhaps somehow positioning jscrollpane or something ? – Marijus Jan 03 '14 at 21:42
  • 1
    @Marijus try setting bounds to the scroll pane instead to the table: `scroller.setBounds(122, 47, 162, 204);`. Not sure if it will work, but you can give it a try. As suggested the best way is through layout managers. Even GUI designers such as NetBeans' make use of them. – dic19 Jan 03 '14 at 21:52
  • 1
    @Marijus: yes, you should re-write your entire GUI. Using absolute positioning means that your program will be very hard to enhance or update, that while it might look good on one system, it will likely look terrible on others. Just learn the layout managers and use them. – Hovercraft Full Of Eels Jan 04 '14 at 04:25