Question

I have a collection of JPanels for different elements: JPanel showPane, seasonsPane, episodesPane, airingsPane
all of which have setLayout set to null and are of fixed size 304x416. I added those JPanels to a JPanel called showViewPanel of size 1280x416 and set up a BoxLayout like so (below is the code in the JFrame):

showViewPanel.setLayout(new BoxLayout(showViewPanel, BoxLayout.X_AXIS));
showViewPanel.setSize(1280, 416);
showViewScroll = new JScrollPane(showViewPanel);
add(showViewScroll);
setSize(304, 416);
setVisible(true);

What I can't figure out is why it does not produce a scrollable view of all the components and instead resizes showViewPanel to match the size of the window. What am I doing wrong?

Was it helpful?

Solution 2

Override the preferredSize of the subpanels to 304x416 instead. The scrollpane relies on the preferred size of the content (which depends on the preferred size of its contents).

The layout manager will set the size of the subpanels depending on their preferred sizes, so your custom ones get overridden. Generally, you should get rid of null layouts and learn to use the layout managers. Absolute placement leads to trouble all the time, and is not worth the hassle even when it does not.

OTHER TIPS

all of which have setLayout set to null and are of fixed size 304x416.

Don't use a null layout!!! Don't manually set the size of a panel!!! Your panels should be using a layout manager so the preferred size will be calculated automatically.

If you want all your panels to be the same size then maybe use a GridLayout for your main panel (instead of the BoxLayout) and then add your child panels to this panel.

Scrollbars will automatically appear when needed if you let the layout managers do their job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top