Reputation: 9040
When you use the method
public boolean mouseDown(Event e, int x, int y)
in Java, what does the Event object do or what is it used for? I am trying to write a program that involves someone clicking on a rectangle created by
g.fillRect(horizontal position,vertical position,height,width);
I presume you use event handling to pick up the click on the rectangle with the mousedown method, but how can u do this? Please provide examples in your answers. I did my research on Google, and found nothing, even with really specific searches. Help greatly appreciated!
Upvotes: 2
Views: 10793
Reputation: 2211
mouseDown is a mouse event. What you need to do is add an event listener to your program, so when the mouse is clicked an event handler calls a method. In this method you want to see if the x,y position of the mouse is within the rectangle.
You will need to implement MouseListener "implements MouseListener"
// import an extra class for the MouseListener
import java.awt.event.*;
public class YourClassName extends Applet implements MouseListener
{
int x = horizontal position;
int y = vertical position;
g.fillRect(x,y,width,height);
addMouseListener(this);
// These methods always have to present when you implement MouseListener
public void mouseClicked (MouseEvent mouseEvent) {}
public void mouseEntered (MouseEvent mouseEvent) {}
public void mousePressed (MouseEvent mouseEvent) {}
public void mouseReleased (MouseEvent mouseEvent) {}
public void mouseExited (MouseEvent mouseEvent) {}
public void mouseClicked (MouseEvent mouseEvent) {
mouseX = mouseEvent.getX();
mouseY = mouseEvent.getY();
if(mouseX > x && mouseY > y && mouseX < x+width && mouseY < y+height){
//
// do whatever
//
}
}
for more... http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseListener.html
Upvotes: 3
Reputation: 33534
As you have asked this
in Java, what does the Event object do or what is it used for?
- First of all there are Event Source
, when any action take place on the Event Source, an Event Object
is thrown to the call back
method.
- Call Back
method is the method inside the Listener
(Interface) which is needed to be implemented by the Class
that implements this Listener.
- The statements inside this call back method will dictate whats needed to be done, when the action is done on the Event Source.
Eg:
Assume
Event Source - Button
When Clicked - Event object is thrown at the call back method
Call back method - actionPerformed(ActionEvent e) inside ActionListener.
- In your example when the mouse button goes down, the x and y co-ordinate gets noted. Then the event object it thrown at its call back method, which needs to be handled by the class that implements this Listener.
- Its better to use mousePressed
method of MouseListener Interface
.
See this link:
Upvotes: 0
Reputation: 24791
The Event object contains information like the
It provides lot of other information as well.
Note: The method is deprecated in favour of processMouseEvent().
Upvotes: 2