I have a panel layout issue that I can’t seem to solve. I have the following code:
public class Test extends ApplicationFrame {
public Test(String title) {
super(title);
JPanel jpanel = new JPanel();
jpanel.setPreferredSize(new Dimension(100 * 2, 300));
jpanel.setBackground(new Color(0xFF0000));
JScrollPane scrollPane = new JScrollPane(jpanel);
scrollPane.setBackground(new Color(0xFF0000));
scrollPane.getViewport().setPreferredSize(new Dimension(100 * 2, 300));
this.add(scrollPane, BorderLayout.WEST);
this.setPreferredSize(new Dimension(500, 500));
}
public static void main(String args[]) {
Test test = new Test("Layout Test");
test.pack();
RefineryUtilities.centerFrameOnScreen(test);
test.setVisible(true);
}
}
to create the following layout:

When I drag the right hand side of the window and move it over into the red JPanel and JScrollPane, I’d like the horizontal scroll bars to appear on the JScrollPane. But currently the window just shrinks without showing the horizontal scroll bar. Is this possible?
I’d like to keep the BorderLayout.WEST since my use case for this is to keep a JFreeChart from stretching when I don’t have a big enough chart to fill the entire window.
There are many reasons not to use
setPreferredSize(), but the critical one here is that the desired result depends on the preferred size of the enclosed components. In particular,ChartPanelhas the defaultFlowLayoutspecified byJPanel, but the chart ignores this and adjusts to fill the space available; you can overridegetPreferredSize()to choose any desired initial geometry.The scroll bars of a
JScrollPaneonly appear when the size of the viewport is smaller than the size of the content.BorderLayout.WESTandBorderLayout.EASTdon’t change, so the scroll bars never appear.Invoking
pack()“causes thisWindowto be sized to fit the preferred size and layouts of its subcomponents.” In the example below, the frame’s size is artificially reduced afterpack()in order to cause the scroll bars to appear.GridLayoutcauses the two panels to be equal is size. Resize the frame to see the effect.Addendum: If you want a
ChartPanelto have a fixed size, add it to aJPanel; the defaultFlowLayoutuses the preferred size.