Search code examples
javaswingscrolljscrollpanejlabel

Scroll JScrollPane while dragging a JLabel that is on that JScrollPane


I have multiple JPanels placed onto a JScrollPane. Right now I have it so that if your mouse is outside of the frame then it will not drag the JPanels.

I need to make it scroll while I moving the component in a direction. (ex. If I grab component and then move to the right all the way to edge of screen the component should move and the JScrollPane should scroll at the same time). Essentially both should be visible while I am dragging and while JScrollPane is (autoscrolling?)

int dX,dY;
public void mousePressed(MouseEvent e)
{
    dX = e.getLocationOnScreen().x - this.getX();
    dY = e.getLocationOnScreen().y - this.getY();
}
public void mouseDragged(MouseEvent e) 
{
    this.scrollRectToVisible(getVisibleRect());
    this.setLocation(e.getLocationOnScreen().x - dX, e.getLocationOnScreen().y - dY);
    dX = e.getLocationOnScreen().x - this.getX();
    dY = e.getLocationOnScreen().y - this.getY();
}

Thats the code for the dragging. The screen (which is a variable) is a JPanel which is what is being sent to the JScrollPane which is contained in a JFrame.


Solution

  • scrollPaneView.setAutoScrolls(true) together with your scroll-to-visible code should work.

    See JComponent#setAutoscrolls javadoc for more information.