Make the JPanel scale equal to the width, but keep a fixed height

I have a JPanel that I put inside a JScrollPane . I manually draw it using paintComponent() , since it is used as a canvas, and I want the panel to automatically match the width of the scroll bar. Then I can use getWidth() in the color code to automatically scale to fit the container. However, I want to be able to manually set my preferred height so that I use the scrollbar's vertical scroll capabilities.

What is the best way to do this? This will obviously work anyway if I could just get the width of the scroll bar in the drawing code, but I don't want to break encapsulation too much with hacked code like getParent() , for example.

+4
source share
2 answers

Let your panel implement Scrollable: getScrollableTracksViewportWidth / Height controls how the viewport handles the size in the horizontal / vertical dimension, respectively. A value of true indicates that the component is forcibly the same size as the viewport (i.e., it does not scroll in that direction), so getWidth () can be used sequentially for scaling.

+4
source

I would like your drawing code to use the width of the horizon itself as the basis for drawing. Then set the scroll area so that it never scrolls horizontally, but only vertically.
Is this good enough? It seems too simple, now I typed it!

0
source

All Articles