Hi, I'm trying to implement a JScrollPane into a JPanel. The JPanel in question handles creation of various shapes on the screen which can be dragged. I want the JScrollPane to adjust it's ScrollBars so the components dragged out of view could be seen by moving the scroll bars. I have tried this: drawPanel = ... some JPanel JScrollPane scrollablePanel = new JScrollPane(); scrollablePanel.getViewport().add(drawPanel); // Make the scrollbars always appear scrollablePanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollablePanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); This simply creates the scroll bars which i cannot move. Maybe i need some kind of listeners which determine the size of the scrollable client. Can anyone please help? Thanks in advance! Phil
Look at this example... I think it does what you want... one tricky thing I had to do was call getParent().validate() whenever the label is dragged and the panel needs to resize. Otherwise the scrollpane won't redraw and relayout everything, and the panel will look like it hasn't changed size.
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
posted 17 years ago
Thanks a lot for the example! I really appreciate it! Phil
Though this post is really old, but I hope someone would catch it up. The tricks for creating JScrollPane dynamically for JPanel works while dragging a JLabel around the panel. But it seems not working if multiple JLabels require scroll pane to be active both vertically and horizontally.
When one JLabel makes horizontal scroller active, if another label is dragged vertically, vertical scroller does not adjust. Keeping 2nd JLabel outside view port, if 1st label is dragged back to normal view (horizontal scroll disappears), then vertical scroll appears and 2nd label is visible. Seems each element of container is not getting attention from JScrollPane.
Any help would be appreciated.
posted 11 years ago
It seems I found the problem what was causing scrolling problem. Rather than overriding getPreferredSize and getSize, I copied the code of getPreferredSize in mouseDragged event handler and called scrollRectToVisible, and setPreferredSize on the panel. This takes care of scrolling adjustment.