How to handle mouse events in JPanel?

L

Leo Smith

Dear All,

I want to write a subclass of JPanel.

The new kind of JPanel can handle Mouse Events so that I can click
inside of it and create rectangles. I have looked at
MouseInputAdapter(abstract class)
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/event/MouseInputAdapter.html

and MouseInputHandler
http://java.sun.com/j2se/1.5.0/docs....html#mousePressed(java.awt.event.MouseEvent)

I still don't know how to do it. I need the information where the mouse
was pressed and where the mouse was released. But I don't know how to
use the methods in above classes to obtain such information.

Thank you very much.

BTW, how can I find out if such a new JPanel has been created by
somebody else and is already available?
 
P

Piet71

I want to write a subclass of JPanel.
The new kind of JPanel can handle Mouse Events so that I can click
inside of it and create rectangles. I have looked at
MouseInputAdapter(abstract class)
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/event/MouseInputAdapter.html

and MouseInputHandler
http://java.sun.com/j2se/1.5.0/docs....html#mousePressed(java.awt.event.MouseEvent)

I still don't know how to do it. I need the information where the mouse
was pressed and where the mouse was released. But I don't know how to
use the methods in above classes to obtain such information.
Add a MouseListener (for example, a class derived from
MouseInputAdapter or MouseAdapter) to your JPanel and override the
mouseXXX methods that you need. To get the position where the Mouse was
clicked, have a look at the getPoint() method (and of course at the
other methods as well!) of the MouseEvent class.
Noe that this is all possible without subclassing JPanel. For what you
seem to have in mind (some kind of drawing application) I would
recommend to use JComponent as a base class to avoid interference of
your drawing with the FlowLayout which comes with JPanel.
HTH, Piet
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top