Why doesn't this work (doesn't show up in GUI)
JTable table=new JTable(20,20);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane tableScrollPane=new JScrollPane(table);
tableScrollPane.setBounds(10,70,540,280);
tableScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
tableScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
add(tableScrollPane);
Whereas this does(does show up in GUI).
JTable table=new JTable(20,20);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane tableScrollPane=new JScrollPane();
tableScrollPane.setBounds(10,70,540,280);
tableScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
tableScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
tableScrollPane.add(table);
add(tableScrollPane);
Why is this the case, shouldn't they both do the same thing?
Why is this the case, shouldn't they both do the same thing?
No.
A JScrollPane contains many components including the scrollbars and a viewport and uses its own internal layout manager to set the location of each component. You can't just "add" a component to the scroll pane because the layout manager doesn't support this.
Read the section from the Swing tutorial on How a Scroll Pane Works for more information.
The component (in this case, JTable) needs to be added to the "viewport" of the scroll pane.
You can use:
JScrollPane scrollPane = new JScrollPane( table );
or
JScrollPane scrollPane = new JScrollPane( );
scrollPanwe.setViewportView( table );