我有一个包含一个主要JPanel(灰色)的JFrame(黑色),这个JPanel包含另外三个JPanel:North和South(红色)和Center one(蓝色)。中心的蓝色JPanel将在程序过程中动态添加大量JPanel(绿色)。当中心JPanel已满时,我希望自动显示一个JScrollbar以向下滚动中心面板并查看它包含的所有子(绿色)面板。有人能帮助我吗?问题是滚动条根本没有出现,如果我将15个绿色JPanel添加到我的蓝色JPanel容器中,我只看到10并且我无法向下滚动。
这是我到目前为止尝试过的代码类型......
JPanel panelNorth = new JPanel(new GridBagLayout());
panelNorth.setPreferredSize(new Dimension(1000,100);
//add some labels and buttons
JPanel panelCenter = new JPanel();
panelCenter.setLayout(new BoxLayout(panelCenter, BoxLayout.Y_AXIS));
panelCenter.setPreferredSize(new Dimension(1000,500)
JPanel panel1 = new JPanel(new GridLayout(1, 10));
panel1.setPreferredSize(new Dimension(1000,50));
panelCenter.add(panel1);
//...etc dynamically
JPanel panelSouth = new JPanel(new GridBagLayout());
panelSouth.setPreferredSize(new Dimension(1000,100);
//add some labels and buttons
JScrollPane scrollPaneCenter = new JScrollPane(panelCenter,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//panelCenter must be scrollable when too many panels are added to panelCenter
//add everything to the main panel container
JPanel panelContainer = new JPanel(new BorderLayout(3,3));
panelContainer.setBorder(new EmptyBorder(5,5,5,5));
panelContainer.add(panelNorth,BorderLayout.NORTH);
panelContainer.add(scrollPaneCenter,BorderLayout.CENTER);
panelContainer.add(panelSouth,BorderLayout.SOUTH);
//add everything to frame
JFrame frame = new JFrame();
frame.add(panelContainer);
谢谢。
编辑: 我改变了
JScrollPane scrollPaneCenter = new JScrollPane(panelCenter,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
到此:
JScrollPane scrollPane = new JScrollPane(panelCentre,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
这就是我得到的:
我现在可以看到它,它位于正确的位置,我无法向下滚动以查看我的其他组件。
答案 0 :(得分:1)
通过切换
来修复它panelCenter.setPreferredSize(new Dimension(1000,500);
与
scrollPane.setPreferredSize(new Dimension(1000,500));