JTable 和 JScrollPane 未按应有的方式显示

JTable and JScrollPane not shown as they should

为什么这不起作用(不显示在 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);

然而确实如此(确实显示在 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?

没有

JScrollPane 包含许多组件,包括滚动条和视口,并使用其自己的内部布局管理器来设置每个组件的位置。您不能只是将组件“添加”到滚动窗格,因为布局管理器不支持此功能。

阅读 How a Scroll Pane Works 上的 Swing 教程部分了解更多信息。

需要将组件(在本例中为 JTable)添加到滚动窗格的“视口”。

您可以使用:

JScrollPane scrollPane = new JScrollPane( table );

JScrollPane scrollPane = new JScrollPane( );    
scrollPanwe.setViewportView( table );