在JFrame上绘制一个矩形

时间:2017-10-17 00:45:33

标签: java swing drawrect rubber-band

我目前的问题是我的矩形没有正确擦除。出于某些原因,当我开始拖动时,我的矩形中已经丢失了一大块: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()));

    }
}

我觉得它与我的startX和startY坐标有关,但我仍然无法弄清楚问题。

0 个答案:

没有答案