I can't drag my boxes using MouseMotionListener, helps are appreciated.
Code:class DragingBoxesPanel extends JPanel implements MouseListener, MouseMotionListener{
private boolean dragging;
private int whichBox; // 0: RED, 1: BLUE 2: NONE
private int lastBox;
private int redX;
private int redY;
private int blueX;
private int blueY;
//...
Code:public void paintComponent(Graphics g) {
// ...
g.setColor(Color.RED);
g.fillRect(redX,redY,50,50);
g.setColor(Color.BLUE);
g.fillRect(blueX,blueY,50,50);
Code:public void mousePressed(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
if(evt.isShiftDown()) {
redX = 5;
redY = 5;
blueX = 75;
blueY = 5;
repaint();
}
else {
if((x>=redX && x<=redX+50 && y>=redY && y<=redY+50) && ((x<blueX || x>blueX+50) && (y<blueY || y>blueY+50))) {
whichBox = 0;
dragging = true;
}
else if((x>=blueX && x<=blueX+50 && y>=blueY && y<=blueY+50) && ((x<redX || x>redX+50) && (y<redY || y>redY+50))) {
whichBox = 1;
dragging = true;
}
else if(x>=redX && x<=redX+50 && y>=redY && y<=redY+50 && x>=blueX && x<=blueX+50 && y>=blueY && y<=blueY+50) {
whichBox = 0;
dragging = true;
}
else {
whichBox = 2;
}
}
}
Code:public void mouseReleased(MouseEvent evt) {
dragging = false;
}
Code:public void mouseDragged(MouseEvent evt) {
if(!dragging) return;
int x = evt.getX();
int y = evt.getY();
if(whichBox == 0) {
redX = x;
redY = y;
repaint();
}
else if(whichBox == 1) {
blueX = x;
blueY = y;
repaint();
}
else { };
}
Code:public DragingBoxesPanel() {
setBackground(Color.WHITE);
addMouseListener(this);
addMouseMotionListener(this);
redX = 5;
redY = 5;
blueX = 75;
blueY = 5;
whichBox = 0;
dragging = false;
}

