How to draw rectangle in a JPanel with the mouse's motion

i have two questoin:

a. in method mousePressed() and mouseDragged(),how to save the initial coordinate of the mouse press?

b.i have saw many applets just draw a rectangle only when the mouse is released,how to let rectangle always show on the panel before the mouse is released?

who can show some code of it? Thanks.

[348 byte] By [starfloat] at [2007-9-26 1:56:47]
# 1

I use a global value for rectangle co-ords which is set by a mouseAdaptor (mousePressed & mouseReleased)

I also have a listener implementing MouseMotionListener to track mouse moved.

I redraw the rectangle each time as the cursor moves. I generate the background ONCE as a BufferedImage and then its just a case of redisplaying the image and drawing over with a rectangle.

Regards,

MArk

markee1 at 2007-6-29 3:12:32 > top of Java-index,Security,Cryptography...
# 2
i have puzzled with it.could you give me some code of implement it?Thanks!starfloat666@hotmail.com
starfloat at 2007-6-29 3:12:32 > top of Java-index,Security,Cryptography...
# 3
The tricky bit is implementing both listners - there are some good demos in the Swing tutorials.MArk
markee1 at 2007-6-29 3:12:32 > top of Java-index,Security,Cryptography...
# 4
Thank you.
starfloat at 2007-6-29 3:12:32 > top of Java-index,Security,Cryptography...
# 5

Draw extends canvas {

boolean drawRect=false

int x1, y1, x2, y2

boolean drawFinal=false

paint(Graphics g) {

if(!drawRect) return

if(drawFinal)

g.setColor(Color.black)

else

g.setColor(Color.blue)

g.drawRect(x1, y1, x2-x1, y2-y1)

}

Listen implements mouseListener, MouseMotionListener {

mouseDragged(MouseEvent e) {

Draw.drawRect = true;

Draw.drawFinal = false;

Draw.x = e.getX();

Draw.y = e.getY();

}

mouseUp(MouseEvent e) {

Draw.drawFinal = true;

}

this is the basic skeleton code for this type of operation. of course you will have to add the listener, and the listener will have to have a reference to the drawer. but otherwise it should do what you want it to do. ohh and the method for mouseUp may not be right. it may have another name, or you may actually have to check the mouseEvent itself for this.

glicious at 2007-6-29 3:12:32 > top of Java-index,Security,Cryptography...