如何将JPanel添加到JScrollPane?

问题描述 投票:0回答:1

我在JPanel添加了一个JScrollPane。但主面板不滚动。我的问题是这样的:

JPanel MainPanel = new JPanel();
MainPanel.setBounds(width/2,height/10,width/5,height/5);
MainPanel.setLayout(null);

JScrollPane scrollPane= new JScrollPane(MainPanel);
scrollPane.setBounds(width/2,height/10,width/5,height/5);
//Added scrollPane to MainFrame Panel
MainFrame.add(scrollPane);

//Added four JPanel to MainPanel
JPanel subPanel1 = new JPanel();
subPanel.setbounds(10,20,50,50);
MainPanel.add(subPanel);

JPanel subPanel2 = new JPanel();
subPanel2.setbounds(50,60,50,50);
MainPanel.add(subPanel2);

JPanel subPanel3 = new JPanel();
subPanel3.setbounds(50,100,50,50);
MainPanel.add(subPanel3);

JPanel subPanel4 = new JPanel();
subPanel4.setbounds(50,60,50,50);
MainPanel.add(subPanel4);

我没有看到subPanel3subPanel4。现在我能够看到垂直滚动条,但它无法正常工作。

java swing layout-manager jscrollpane null-layout-manager
1个回答
0
投票

我建议你使用布局而不是setBounds()。 GridBagLayout,GridLayout,FlowLayout,BoxLayout和BorderLayout将非常有用。文档在这里:https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

并将其附加在代码的底部:

scrollPane.getViewport().setView(MainPanel);
© www.soinside.com 2019 - 2024. All rights reserved.