0

I'm currently having a problem with why my rectangle isn't erasing properly. For some reason when I begin the drag there is already a chunk of my rectangle missing as so: enter image description here

@Override
public void mousePressed(MouseEvent e) {
    startX = e.getX();
    startY = e.getY();

    // initialize lastX, lastY
    lastX = startX;
    lastY = startY;

}

@Override
public void mouseDragged(MouseEvent e) {
    // Implement rubber-band cursor
    Graphics g = drawingPanel.getGraphics();
    //g.setColor(Color.black);

    g.setXORMode(drawingPanel.getBackground());

    // REDRAW the line that was drawn 
    // most recently during this drag
    // XOR mode means that yellow pixels turn black
    // essentially erasing the existing line
    if(drawMode == Mode.LINE) {
        g.drawLine(startX, startY, lastX, lastY);
        g.drawLine(startX, startY, e.getX(), e.getY());

    }
    // draw line to current mouse position
    // XOR mode: yellow pixels become black
    // black pixels, like those from existing lines, temporarily become
    // yellow
    else if(drawMode == Mode.RECTANGLE) {
        g.drawRect(startX, startY, lastX, lastY);
        g.drawRect(startX, startY, e.getX(), e.getY());

    }
    lastX = e.getX();
    lastY = e.getY();   

}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub
    if(drawMode == Mode.LINE) {
        allShapes.add(new Line(startX, startY, arg0.getX(), arg0.getY()));

    }else if(drawMode == Mode.RECTANGLE){
        allShapes.add(new Rectangle(startX, startY, arg0.getX(), arg0.getY()));

    }
}

I have a feeling it has to do with my startX and startY coordinates but I still can't figure out the problem.

Ativelox
  • 27
  • 5
Michael
  • 45
  • 5
  • 2
    `Graphics g = drawingPanel.getGraphics();` is not how custom painting works - You're getting a snap shot of the last paint pass which occurred, which could changed by the repaint sub system, effectively erasing everything you've already painted. You should be overriding `paintComponent` and update the information it needs in order to paint what you want – MadProgrammer Oct 17 '17 at 01:06
  • 3
    Start by having a look at [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) and [Painting in Swing](http://www.oracle.com/technetwork/java/painting-140037.html) for a better understand of how painting works – MadProgrammer Oct 17 '17 at 01:07
  • 1
    Instead of `setXORMode()`, this [example](https://stackoverflow.com/a/42829574/230513) invokes `repaint()`. – trashgod Oct 17 '17 at 01:39

0 Answers0