Home > Software > Swing tip: Move by dragging

Swing tip: Move by dragging

A frame can be moved by dragging it from the title bar. But if you have a window without the title bar or you want to move it by dragging from wherever you want, this is the tip for you.
The MouseListener and MouseMotionListener will do the trick. They will be added to the JWindow that we want to move by dragging.

import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.*;

public class DragMove implements MouseListener, MouseMotionListener {

public static DragMove install(Component c) {
DragMove x = new DragMove();
return x;

private Point start;

public void mouseClicked(MouseEvent e) {

public void mousePressed(MouseEvent e) {
start = e.getPoint();

public void mouseReleased(MouseEvent e) {

public void mouseEntered(MouseEvent e) {

public void mouseExited(MouseEvent e) {

public void mouseDragged(MouseEvent e) {
Point p = e.getLocationOnScreen();
Component c = e.getComponent();
c.setLocation((int)(p.getX() - start.getX()), (int)(p.getY() - start.getY()));

public void mouseMoved(MouseEvent e) {

Just a few explanations. When the mouse button is pressed, then the starting location relative to the window is stored. Then as the window is dragged, its location is moved on the screen relative to this starting point. And the window is repainted.
Pretty fast and simple enough.

Categories: Software Tags: ,
  1. June 14, 2010 at 11:36 am

    great info,, thanks

  1. July 19, 2009 at 2:43 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: