Dragging buttons

I am relatively new to swing and need some help or direction in respect to dragging buttons. Specifically, dragging a button and placing it in between other buttons. I have an array of buttons currently, and I want to be able to pick any one of them, and drag them in between another. I have read up a bit on DnD, but I dont think its what I need, since im dragging buttons within the same frame.

Anyways, i just need direction. Any help is greatly appreciated.

[475 byte] By [MuriloGa] at [2007-11-26 18:03:51]
# 1

Check out my Draggable class

You are free to use and modify this class, but please don't change the package or take credit for it as your own work

tjacobs.ui.Draggable

================

package tjacobs.ui;

import java.awt.Component;

import java.awt.Cursor;

import java.awt.Dimension;

import java.awt.Point;

import java.awt.Window;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

/**

* tjacobs.ui.Draggable

* Makes a component draggable. Does not work if there's a layout manager

* messing with things

* <code>

* usage:

* Component c = ...

* new Draggable(c);

* parent.add(c);

* </code>

*/

public class Draggable extends MouseAdapter implements MouseMotionListener {

Point mLastPoint;

Component mDraggable;

public Draggable(Component w) {

w.addMouseMotionListener(this);

w.addMouseListener(this);

mDraggable = w;

}

public Draggable(Window w, Component drag) {

drag.addMouseMotionListener(this);

drag.addMouseListener(this);

mDraggable = w;

}

public void mousePressed(MouseEvent me) {

if (mDraggable.getCursor().equals(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))) {

mLastPoint = me.getPoint();

}

else {

mLastPoint = null;

}

}

private void setCursorType(Point p) {

Point loc = mDraggable.getLocation();

Dimension size = mDraggable.getSize();

if ((p.y + WindowUtilities.RESIZE_MARGIN_SIZE < loc.y + size.height) && (p.x + WindowUtilities.RESIZE_MARGIN_SIZE < p.x + size.width)) {

mDraggable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

}

}

public void mouseReleased(MouseEvent me) {

mLastPoint = null;

}

public void mouseMoved(MouseEvent me) {

setCursorType(me.getPoint());

}

public void mouseDragged(MouseEvent me) {

int x, y;

if (mLastPoint != null) {

x = mDraggable.getX() + (me.getX() - (int)mLastPoint.getX());

y = mDraggable.getY() + (me.getY() - (int)mLastPoint.getY());

mDraggable.setLocation(x, y);

}

}

}

tjacobs01a at 2007-7-9 5:34:06 > top of Java-index,Security,Event Handling...