Search code examples
javaswingjpaneljscrollpanelayout-manager

Make a JPanel scale to fit width but keep a fixed height


I have a JPanel which I'm placing inside of a JScrollPane. I am manually painting it using paintComponent(), since it's being used as a canvas, and I want the panel to automatically fit to the width of the scroll pane. I can then use getWidth() in the painting code to automatically scale to fit the container. However, I want to be able to manually set the preferred height so the I make use of the scroll pane's vertical scrolling capabilities.

What's the best way to do this? This would obviously still work if I was just able to get the width of the scroll pane in the painting code, but I don't want to break encapsulation too much with hacky code like getParent().


Solution

  • Let your panel implement Scrollable: the getScrollableTracksViewportWidth/Height control how the viewport handles the sizing in the horizontal/vertical dimension, respectively. A value of true indicates that the component is forced to the same size as viewport (that is, no scrolling in that direction), so getWidth() can be consistently used for scaling.