Search code examples
javaswingjpaneljscrollpanepreferredsize

Java: how can I change the size of a JPanel that's inside a JScrollPane?


I have a JPanel inside a JScrollPane, and that JPanel must be able to change width when the users moves the mouse wheel. I wrote the event listener for the mouse wheel, which works, but the JScrollPane seems to force a different (constant) size on the inner JPanel. I found a ScrollablePanel class online, but it seems to have the same problem. How can I fix it?

Thanks :)


Solution

  • Ok, I seem to have found the solution by pure luck, so I'm posting it here in case it's use to someone:

    -set the size of the JPanel with setPreferredSize instead of setSize -use scrollPane.setViewportView(panel) every time to update the scrollbars

    doesn't make sense to me, but it works, so I'm happy with it.