Reputation: 125
I have one JFrame (black) that contains one main JPanel (grey), this JPanel contains three other JPanels : North and South (red) and the Center one (blue). The blue JPanel in the center will have lots of JPanels (green) added dynamically to it during the course of the program. When the Center JPanel is full I would like a JScrollbar to appear automatically to scroll down the Center Panel and see all the child (green) panels it contains. Can somebody help me? The problem is that the scrollbar isn't appearing at all, if i add 15 green JPanels to my blue JPanel container, i only see 10 and i can't scroll down.
This is the type of code i have tried so far...
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);
Thank you.
EDIT: I changed
JScrollPane scrollPaneCenter = new JScrollPane(panelCenter,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
to this :
JScrollPane scrollPane = new JScrollPane(panelCentre,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
And this is what i get:
I can see it now, it's in the right place, i just can't scroll down to see my other components.
Upvotes: 2
Views: 2671
Reputation: 125
Fixed it by switching
panelCenter.setPreferredSize(new Dimension(1000,500);
with
scrollPane.setPreferredSize(new Dimension(1000,500));
Upvotes: 1