2

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.

TT.
  • 15,774
  • 6
  • 47
  • 88
Cherple
  • 725
  • 3
  • 10
  • 24
  • See: https://stackoverflow.com/questions/36163364/jscrollpane-with-fixed-width/36164503#36164503 – camickr Jul 16 '20 at 14:59

1 Answers1

1

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
Guillaume
  • 14,306
  • 3
  • 43
  • 40
  • Hi, i tried your suggestion, the result is as shown in my edit. The scrollbar is no longer there but the panel within the jscrollpane still has its width exceeding the jscrollpane, thus a section of the panel is now no longer viewable. – Cherple Jul 21 '20 at 01:50