...
private Point top_leftPoint = new Point(), top_rightPoint = new Point(),
bottom_leftPoint = new Point(), bottom_rightPoint = new Point();
private Point top_leftPointC = new Point(), top_rightPointC = new Point(),
bottom_leftPointC = new Point();
private Rectangle rectContainer = new Rectangle();
...
@Override
public void mouseDragged(final MouseEvent e) {
...
stayInContainer(label);
}
};
...
public void stayInContainer(final Component comp) {
// if the plate is too far in right-direction, move it back
if (!isInContainer(comp)) {
double x = top_rightPoint.getX();
double xC = top_rightPointC.getX();
if (x > xC) {
comp.setLocation((int) (top_leftPoint.getX() + xC - x), (int) top_leftPoint.getY());
}
}
// if the plate is too far in left-direction, move it back
if (!isInContainer(comp)) {
double x = top_leftPoint.getX();
double xC = top_leftPointC.getX();
if (x < xC) {
comp.setLocation((int) (top_leftPoint.getX() + xC - x), (int) top_leftPoint.getY());
}
}
// if the plate is too far in top-direction, move it back
if (!isInContainer(comp)) {
double y = top_leftPoint.getY();
double yC = top_leftPointC.getY();
if (y < yC) {
comp.setLocation((int) top_leftPoint.getX(), (int) (top_leftPoint.getY() + yC - y));
}
}
/* if the plate is is too far in bottom-direction, move it back */
if (!isInContainer(comp)) {
double y = bottom_leftPoint.getY();
double yC = bottom_leftPointC.getY();
if (y > yC) {
comp.setLocation((int) top_leftPoint.getX(), (int) (top_leftPoint.getY() + yC - y));
}
}
}
private boolean isInContainer(final Component comp) {
Container container = comp.getParent();
rectContainer.width = container.getWidth();
rectContainer.height = container.getHeight();
int wC = (int) rectContainer.width;
int hC = (int) rectContainer.height;
top_leftPointC.x = rectContainer.x;
top_leftPointC.y = rectContainer.y;
top_rightPointC.x = (int) (top_leftPointC.getX() + wC);
top_rightPointC.y = (int) top_leftPointC.getY();
bottom_leftPointC.x = (int) top_leftPointC.getX();
bottom_leftPointC.y = (int) top_leftPointC.getY() + hC;
int w = comp.getWidth();
int h = comp.getHeight();
top_leftPoint.x = comp.getX();
top_leftPoint.y = comp.getY();
top_rightPoint.x = (int) top_leftPoint.getX() + w;
top_rightPoint.y = (int) top_leftPoint.getY();
bottom_leftPoint.x = (int) top_leftPoint.getX();
bottom_leftPoint.y = (int) top_leftPoint.getY() + h;
bottom_rightPoint.x = (int) top_leftPoint.getX() + w;
bottom_rightPoint.y = (int) top_leftPoint.getY() + h;
if (!rectContainer.contains(top_leftPoint)) {
return false;
}
if (!rectContainer.contains(top_rightPoint)) {
return false;
}
if (!rectContainer.contains(bottom_leftPoint)) {
return false;
}
if (!rectContainer.contains(bottom_rightPoint)) {
return false;
}
return true;
}
...