Java tutorial
//package com.java2s; /* * Copyright (C) 2006-2011 by Olivier Chafik (http://ochafik.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.event.MouseInputAdapter; public class Main { public static void addMiddleButtonDragSupport(Component targetComponent) { MouseInputAdapter mia = new MouseInputAdapter() { int m_XDifference, m_YDifference; boolean m_dragging = false; public void mouseDragged(MouseEvent e) { if (!m_dragging) return; Component target = e.getComponent(); Container c = target.getParent(); if (c instanceof JViewport) { JViewport jv = (JViewport) c; Point p = jv.getViewPosition(); int newX = p.x - (e.getX() - m_XDifference); int newY = p.y - (e.getY() - m_YDifference); int maxX = target.getWidth() - jv.getWidth(); int maxY = target.getHeight() - jv.getHeight(); if (newX < 0) newX = 0; if (newX > maxX) newX = maxX; if (newY < 0) newY = 0; if (newY > maxY) newY = maxY; jv.setViewPosition(new Point(newX, newY)); } } Cursor oldCursor; public void mousePressed(MouseEvent e) { if (SwingUtilities.isMiddleMouseButton(e)) { m_dragging = true; oldCursor = e.getComponent().getCursor(); e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); m_XDifference = e.getX(); m_YDifference = e.getY(); } } public void mouseReleased(MouseEvent e) { if (m_dragging) { e.getComponent().setCursor(oldCursor); m_dragging = false; } } }; targetComponent.addMouseMotionListener(mia); targetComponent.addMouseListener(mia); } }