Binding JPanel's width to JScrollPane's width to prevent auto resize

Viewed 74

I have code that looks something like this:

JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(panel);
scrollPane.setHorizontalScrollBarPolicy(
           JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

What happens is when the component in the panel becomes too wide, a horizontal scroll bar in the scrollPane appears and the user has to scroll left or right. The thing is, the component in panel is actually resizable, but because it's a JScrollPane, it maximizes.

Question: Is there any way I can bind the panel's width property to scrollPane's width property? So that the components inside the panel won't exceed the panel's width?

Below shows what it looks like:

Panel width exceeding jscrollpane

With the horizontal scroll bar policy set to never, the scroll bar disappears but the panel width remains the same, but now a section of the panel is no longer viewable.

1 Answers

You can change the scroll bar policy using the setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy methods or from the constructor JScrollPane(Component, int, int)

Quoting the Oracle documentation, the policies are:

  • VERTICAL_SCROLLBAR_AS_NEEDED
  • HORIZONTAL_SCROLLBAR_AS_NEEDED
  • VERTICAL_SCROLLBAR_ALWAYS
  • HORIZONTAL_SCROLLBAR_ALWAYS
  • VERTICAL_SCROLLBAR_NEVER
  • HORIZONTAL_SCROLLBAR_NEVER
Related