Search code examples
javaswinguser-interfacelayoutjscrollpane

How does a JLabel or JButton tell a JScrollPane that view size has changed?


How does a JLabel or JButton notify a JScrollPane that the view size has changed (for example when an icon has been set) so it can determine whether showing scrollbars are necessary?

How could I implement similar behaviour to display an image with a simple JPanel without resorting to the aforementionned components?

P.S: I've looked through the source code and so far all I see is that a Component is referred to as "view" and is passed on to a JView or JViewport which registers some listeners. From there on things seem unclear.


Solution

  • As noted in the JScrollPane API, unless you change the policy, "both horizontal and vertical scrollbars appear whenever the component's contents are larger than the view." Once pack() has sized the Window "to fit the preferred size and layouts of its subcomponents," any subsequent changes are seen by the scroll pane when the container is validated and repainted. See Painting in AWT and Swing for more.