how to draw rectangle on java applet using mouse drag event

前端 未结 3 2029
北海茫月
北海茫月 2021-01-21 11:19

i am using java. i want to draw rectangle based on mousedrag event. if user dragging the mouse, then the rectangle on the applet should increase or decrease basing on current mo

3条回答
  •  自闭症患者
    2021-01-21 11:24

    homework?

    basically what you need to do is:

    1. on mouse down keep the mouse-down coordinates and repaint
    2. on mouse move keep current mouse coordinates and repaint
    3. on mouse up, nullify the mouse-down coordinates to indicate there is no rect, and repaint.
    4. on paint, draw background and then rect between mousedown and cur-mouse coordinates.

    if you don't want to keep a background image, you can do a trick with the Graphics xor function, drawing the same rect twice will erase the old rect, so you can use it to restore the old image straight on the graphics object.

    Edit: code xor usage sample:

    public void paint(Graphics g)
    {
       g.setXORMode(Color.black);
       // draw old rect if there is one. this will erase it
       // draw new rect, this will draw xored
       g.setDrawMode(); // restore normal draw mode
    }
    

    Xor has the an interesting property:

    xor(xor(x)) = x
    

    so xoring the same pixel twice restores it's original color.

提交回复
热议问题