import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class AppWindow extends Frame {
String keyMessage = "";
String MouseMsg = "";
int mouseX = 10;
int mouseY = 40;
int locX = 0;
int locY = 0;
public AppWindow() {
addMouseListener(new MyMouseAdaptor(this));
}
public void paint(Graphics g) {
g.drawString(keyMessage, mouseX, mouseY);
g.drawString(MouseMsg, locX, locY);
}
public static void main(String[] args) {
AppWindow appWindow = new AppWindow();
appWindow.setSize(400, 400);
appWindow.setVisible(true);
}
}
class MyMouseAdaptor extends MouseAdapter implements MouseListener {
AppWindow appWindow;
public MyMouseAdaptor(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent e) {
this.appWindow.MouseMsg = "Mouse Pressed at : " + e.getX() + ", "
+ e.getY();
this.appWindow.locX = e.getX();
this.appWindow.locY = e.getY();
this.appWindow.repaint();
}
}
Dear All
I have a weird question. I know everything in the above code yet I am missing something. How Java knows when the mousePressed Event occurred? I need to find the answer for my own logic. Where is the code written that says
when the user press the mouse -- > trigger the method "public void mousePressed(MouseEvent e)" and do what is inside it
Thanks
This is the code that registers to look out for mouse events:
public AppWindow() {
addMouseListener(new MyMouseAdaptor(this));
}
This is your class that extends MouseAdaptor and listens for events:
class MyMouseAdaptor extends MouseAdapter implements MouseListener {
AppWindow appWindow;
public MyMouseAdaptor(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent e) {
this.appWindow.MouseMsg = "Mouse Pressed at : " + e.getX() + ", "
+ e.getY();
this.appWindow.locX = e.getX();
this.appWindow.locY = e.getY();
this.appWindow.repaint();
}
}
MouseAdaptor:
An abstract adapter class for receiving mouse events. The methods in this class are empty. This class exists as convenience for creating listener objects.
Mouse events let you track when a mouse is pressed, released, clicked, moved, dragged, when it enters a component, when it exits and when a mouse wheel is moved.
Extend this class to create a MouseEvent (including drag and motion events) or/and MouseWheelEvent listener and override the methods for the events of interest. (If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about.)
Create a listener object using the extended class and then register it with a component using the component's addMouseListener addMouseMotionListener, addMouseWheelListener methods. The relevant method in the listener object is invoked and the MouseEvent or MouseWheelEvent is passed to it in following cases:
when a mouse button is pressed, released, or clicked (pressed and released)
when the mouse cursor enters or exits the component
when the mouse wheel rotated, or mouse moved or dragged
Link
MouseListener:
The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener.)
The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest).
The listener object created from that class is then registered with a component using the component's addMouseListener method. A mouse event is generated when the mouse is pressed, released clicked (pressed and released). A mouse event is also generated when the mouse cursor enters or leaves a component. When a mouse event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.
Link
Now after you have read this, I think you will be able to make some changes to your program because when you implement MouseListener interface you have to define all of the methods in it..
There are actually two event classes associated with the mouse: MouseEvent and MouseMotionEvent. There are also two listener interfaces, MouseListener and MouseMotionListener. The MouseListener interface declares the methods
public void mousePressed(MouseEvent evt);
public void mouseReleased(MouseEvent evt);
public void mouseClicked(MouseEvent evt);
public void mouseEntered(MouseEvent evt);
public void mouseExited(MouseEvent evt);
and the MouseMotionListener declares
public void mouseMoved(MouseEvent evt);
public void mouseDragged(MouseEvent evt);
Any component can generate mouse events. An object that wants to respond to these events must implement one or both of the listener interfaces. It must also register itself with the component by calling the component's addMouseListener() and/or addMouseMotionListener() methods. Note that an object that implements MouseListener must provide definitions for all five of the methods in that interface, even if a definition consists just of an empty set of braces. Similarly, an object that implements MouseMotionListener must define both the mouseMoved() and the mouseDragged() methods.
A component calls mousePressed() whenever one of the buttons on the mouse is pressed while the mouse cursor is over that component. It will then call the mouseReleased() method when the button is released -- even if the cursor has moved outside of the component by that time. The mouseClicked() method is called if the button is pressed and released at the same point; it is called in addition to mousePressed() and mouseReleased(). If you simply want to respond to mouse clicks, you should probably do so in the mousePressed() routine, and leave the definitions of mouseReleased() and mouseClicked() empty.
Source
Related
Edit:
I have an application that uses a swing Timer to control when an action listener interface fires. The mouse logic works but occasionally will not detect a click. Below is my commented code.
public class Board extends JPanel implements MouseListener, MouseMotionListener, ActionListener
{
private MainMenu mainMenu = new MainMenu();
private static String State; /*Makes the control flow simpler, just checking
strings that describe the state. All the states are contained in GameState class.*/
public Board()
{
this.addMouseListener(this);
this.addMouseMotionListener(this);
setVisible(true);
mainMenu.initLogIn(); /*This just loads the button images*/
Timer timer = new Timer(12, this); /*(millisecond delay, tells this class
to update any actionlistener (mouselistener etc)*/
timer.start();
}
public void paint(Graphics G)
{
super.paint(G);
Graphics G2d = (Graphics2D)G;
/*Main menu paint logic*/
// This paints buttons from mainMenu class on screen
G.drawImage(mainMenu.getTopic1().getspriteImage(),
mainMenu.getTopic1().getxCoord(),
mainMenu.getTopic1().getyCoord(),this);
G.drawImage(mainMenu.getTopic2().getspriteImage(),
mainMenu.getTopic2().getxCoord(),
mainMenu.getTopic2().getyCoord(), this);
G.drawImage(mainMenu.getTopic3().getspriteImage(),
mainMenu.getTopic3().getxCoord(),
mainMenu.getTopic3().getyCoord(),this);
/*Shows mouse input worked by changing the background color*/
if (State == GameState.MAINMENU_TOPIC1)
{
setBackground(Color.BLACK);
}
if (State == GameState.MAINMENU_TOPIC2)
{
setBackground(Color.BLUE);
}
if (State == GameState.MAINMENU_TOPIC3)
{
setBackground(Color.GRAY);
}
repaint(); //tells paint to repaint, which allows gui to update
}
#Override
public void mouseClicked(MouseEvent e)
{
Point point = e.getPoint();
/*This contains the logic to change State based on mouse clicks*/
if(mainMenu.getTopic1().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC1;
}
if(mainMenu.getTopic2().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC2;
}
if(mainMenu.getTopic3().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC3;
}
}
So, I am unsure why mouse clicks would not always be detected. I know there is a chance that the time allocated to update the action listeners could be too short. However, there is not very much code for the machine to loop through, so I figure this is not the problem. Any thoughts on what might cause the mouse to behave this way?
Also, I will definitely implement this later using JButtons. I am sure that would help clean up my code on the larger project
Thanks for the comments, and I hope this clears up the majority of the questions.
A mouse "click" may essentially be a double or triple click. You can get that by using evt.clickCount. It will coalite as one event.
If you want to get every "press", use mousePressed() instead.
I am trying to create a mouse listener class, simply for detecting mouse clicks. My code
package game.input;
import java.awt.event.*;
import java.awt.*;
public class Mouse implements MouseAdapter{
public Mouse(Component c){
c.addMouseListener(this);
}
public boolean mouseClicked(MouseEvent e) {
return true;
}
}
is giving me two errors:
"Interface expected here", pointing to the MouseAdapter
"Method addMouseListener in class Component cannot be applied to given types", pointing to the c.addMouseListener(this)
How can I solve this two problems and accomplish the simple task of creating a detector for mouse clicks? This is the first time I write a MouseListener, so any other comments about mistakes I have done are welcome.
MouseAdapter is a class not a interface, you need to use extends instead of implements
public class Mouse extends MouseAdapter{
Take a look at
What Is a Class?
What Is an Interface?
How to Write a Mouse Listener
For more details
FYI...
public boolean mouseClicked(MouseEvent e) {
Will never be called, as it does not meet the requirements of the MouseListener interface contract, it should be...
#Override
public void mouseClicked(MouseEvent e) {
I am trying to develop a very basic game and it involves mouse. So what i am trying to do is getting coordinates of mouse to write a integer. I searched internet and find this.
mouse_x=MouseInfo.getPointerInfo().getLocation().getX();
mouse_y=MouseInfo.getPointerInfo().getLocation().getY();
It partially worked and gave me coordinates of mouse on desktop. But what i need is coordinates of mouse on frame. So if only i knew the coordinates of frame's starting (0,0) point (not the window's. the white area without toolbars.) I could calculate mouse's coordinates.
Thanks in advance.
Or if thats not possible i could use how to develop it in fullscreen.
And i need to know location of mouse always. It should refresh position when i run it in a never ending while loop.
I just use e.getPoint() which returns the point of the mouse clicked. You could either have your Frame implement MouseListener of you can register a MouseListener to the frame if it is not the main GUI component.
public class MyFrame extends JFrame implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
int x = (int) p.getX();
int y = (int) p.getY();
// do something withe the x and y points
}
}
If you do the above, you also need to override the other MouseListener methods. Though you don't need to implement any action for them
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
If your GUI class didn't extend JFrame, then you can just register the listener to the Frame, in which case you only need to use the MouseAdapter, which allows you to just implement 0 or more action method (i.e. just mouseClicked)
frame.addMouseListener(new MouseAdapter() {
void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
int x = (int) p.getX();
int y = (int) p.getY();
// do somthing withe the x and y points
}
});
Edit for MouseMotionListener
"I want to know location of mouse always not just when clicked."
If you wan't to know the location of the mouse at any given time, you should implement MouseMotionListener and override the mouseDragged and mouseMoved
public class MyFrame extends JFrame implements MouseMotionListener {
....
public void mouseMoved(MouseEvent e){
Point p = e.getPoint();
int x = (int) p.getX();
int y = (int) p.getY();
// do something withe the x and y points
}
public void mouseDragged(MouseEvent e){
}
}
The mouseMoved will fire an event every time the mouse is moved, and the mouseDragged will fire an event whenever the mouse is dragged
You need to add a MouseListener to your JFrame and then you can just get the relative coordinates with MouseEvent.getPoint
frame.addMouseListener(new MouseAdapter() {
void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint());
}
});
If you, for some obscure reason, need the coordinates in a situation when mouse events are not available (in which case, take a look at the other answers), you can use SwingUtilities.convertPointFromScreen() to convert the coordinates from MouseInfo to the coordinate system of a Component.
I have a Swing app with a glass pane over a map.
It paints dots at certain positions. When I click somewhere on the map, and the glass pane receives the message CONTROLLER_NEW_POLYGON_MARK I
want do display an additional dot at the position specified in the event data (see MyGlassPane.propertyChange).
The glass pane class is called MyGlassPane. Using the debugger I validated that addPointToMark is actually called in propertyChange.
But no additional dots appear on the screen.
How can I change the code so that PointSetMarkingGlassPane.paintComponent is called whenever an event (IEventBus.CONTROLLER_NEW_POLYGON_MARK) is fired?
public class PointSetMarkingGlassPane extends JComponent implements IGlassPane {
private final ILatLongToScreenCoordinatesConverter latLongToScreenCoordinatesConverter;
private final List<Point.Double> pointsToMark = new LinkedList<Point.Double>();
public PointSetMarkingGlassPane(final ILatLongToScreenCoordinatesConverter aConverter) {
this.latLongToScreenCoordinatesConverter = aConverter;
}
protected void addPointToMark(final Point.Double aPoint)
{
if (aPoint != null)
{
pointsToMark.add(aPoint);
}
}
#Override
protected void paintComponent(final Graphics aGraphics) {
for (final Point.Double pointToMark : pointsToMark)
{
final Point positionInScreenCoords = latLongToScreenCoordinatesConverter.getScreenCoordinates(pointToMark);
drawCircle(aGraphics, positionInScreenCoords, Color.red);
}
}
private void drawCircle(Graphics g, Point point, Color color) {
g.setColor(color);
g.fillOval(point.x, point.y, 10, 10);
}
}
public class MyGlassPane extends PointSetMarkingGlassPane implements PropertyChangeListener {
public MyGlassPane(ILatLongToScreenCoordinatesConverter aConverter) {
super(aConverter);
addPointToMark(DemoGlassPane.ARTYOM);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (IEventBus.CONTROLLER_NEW_POLYGON_MARK.equals(evt.getPropertyName()))
{
addPointToMark((Point.Double)evt.getNewValue());
invalidate();
}
}
}
As I think invalidate() only flags your component to check sizes and layout. You should call repaint() to repaint your pane.
Also I am wondering why you use propertyChangeListener for mouse clicks. I would prefer just simple mouse listener + MouseAdapter and MouseEvent x, y, buttons state.
invalidate() probably won't help you, as it flags a component for layout changes, not painting changes. Why not call repaint() instead?
For better performance, you could call the repaint method which takes a Rectangle (or four ints representing a rectangle), so that only the newly added point is repainted; I would suggest changing the return type of addPointToMark from void to java.awt.Point, and have it return the result of latLongToScreenCoordinatesConverter.getScreenCoordinates, so MyGlassPane can derive a rectangle from that Point which can then be passed to a repaint method.
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!
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
The Event object contains information like the
x and y coordinates of the event,
The target component on which the event happened
when the even happened
It provides lot of other information as well.
Note: The method is deprecated in favour of processMouseEvent().
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:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseListener.html#mousePressed%28java.awt.event.MouseEvent%29