import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BoxDragging {
public static void main(String[] s) {
JFrame frame = new JFrame();
frame.setBounds(0, 0, 500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BoxDragging().new BoxPanel());
frame.setVisible(true);
}
class BoxPanel extends JPanel {
private List<Box> boxList;
private int currentBox = -1;
private Point clickPoint;
private Point position;
public BoxPanel() {
boxList = new ArrayList<Box>();
Box box = new Box(50, 50);
box.setLocation(50, 50);
boxList.add(box);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
currentBox = -1;
}
public void mousePressed(MouseEvent e) {
for (int i=boxList.size()-1; i>=0; i--) {
clickPoint = e.getPoint();
Box box = boxList.get(i);
if (box.getBounds().contains(clickPoint)) {
currentBox = i;
position = new Point(box.getBounds().x, box.getBounds().y);
return;
}
}
}
public void mouseReleased(MouseEvent e) {
currentBox = -1;
}
});
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (currentBox!= -1) {
Box box = boxList.get(currentBox);
Point p = e.getPoint();
box.setLocation(position.x + (p.x - clickPoint.x), position.y + p.y - clickPoint.y);
repaint();
}
}
public void mouseMoved(MouseEvent e) {}
});
}
public void addBox(Box box) {
this.boxList.add(box);
this.repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Box box: boxList)
box.paintComponent(g);
}
}
class Box {
private int x, y;
private int width, height;
private Stroke stroke = new BasicStroke(3);
private Rectangle bounds;
public Box(int width, int height) {
this.width = width;
this.height = height;
this.setLocation(0, 0);
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
bounds = new Rectangle(x, y, width, height);
}
public Rectangle getBounds() {
return bounds;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
g2.setStroke(stroke);
g2.setColor(Color.WHITE);
g2.fillRoundRect(x, y, width, height, 5, 5);
g2.setColor(Color.DARK_GRAY);
g2.drawRoundRect(x, y, width, height, 5, 5);
g2.dispose();
}
}
}