Java JScrollPane makeComponentDragScrollable(final JComponent component)

Here you can find the source of makeComponentDragScrollable(final JComponent component)

Description

Makes a component drag-scrollable.

License

Apache License

Parameter

Parameter Description
component component to be made drag-scrollable

Declaration

public static void makeComponentDragScrollable(final JComponent component) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.awt.Cursor;
import java.awt.Rectangle;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;

public class Main {
    /**/*  w  w  w .ja va 2 s.c o  m*/
     * Makes a component drag-scrollable.
     * 
     * <p>
     * If a component is drag-scrollable and the user tries to drag the component, it will be scrolled if it is added to a scroll pane. Also changes the mouse
     * cursor to "MOVE" over this component.
     * </p>
     * 
     * @param component component to be made drag-scrollable
     */
    public static void makeComponentDragScrollable(final JComponent component) {
        final MouseAdapter dragHandler = new MouseAdapter() {
            int dragStartX, dragStartY;

            @Override
            public void mousePressed(final MouseEvent event) {
                if ((event.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                    dragStartX = event.getXOnScreen();
                    dragStartY = event.getYOnScreen();
                }
            };

            @Override
            public void mouseDragged(final MouseEvent event) {
                if ((event.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                    final Rectangle visibleRect = component.getVisibleRect();
                    visibleRect.x += (dragStartX - event.getXOnScreen()) * 2;
                    visibleRect.y += (dragStartY - event.getYOnScreen()) * 2;
                    component.scrollRectToVisible(visibleRect);
                    dragStartX = event.getXOnScreen();
                    dragStartY = event.getYOnScreen();
                }
            }
        };

        component.addMouseListener(dragHandler);
        component.addMouseMotionListener(dragHandler);

        component.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
    }
}

Related

  1. getScrollPaneViewportSize(JScrollPane panel)
  2. hasParentScrollPane(JComponent component)
  3. initScrollPane(JScrollPane scrollPane)
  4. isHorizontalScrollBarHiddenAlways(JScrollPane pane)
  5. isScrolledToBottom(final JScrollPane scrollPane)
  6. makeListInScrollPane(Collection items, Function namer)
  7. makeVScroller(Component c)
  8. moveEnd(JScrollPane pane)
  9. newJScrollPane(String title, Component c)