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.
Related
I have a school assignment to make a program which creates a small window, and when you move the mouse around without clicking it displays the coordinates above in BLACK text, and when you hold and drag the mouse it displays the coordinates above in RED text. I have the program working so it displays the coordinates above the mouse for both events but I'm not sure how to change the color to red when the mouse is being held down. Here is what I have so far:
class MyFrame extends Frame{
int x;
int y;
public void paint(Graphics g){
g.drawString(
"" + x + ", " + y, x, y);
}
}
class MyMouseListener extends MouseMotionAdapter{
MyFrame ref;
MyMouseListener(MyFrame mFrame){
ref = mFrame;
}
public void mouseDragged(MouseEvent e){
ref.x = e.getX();
ref.y = e.getY();
ref.repaint();
}
public void mouseMoved(MouseEvent e){
ref.x = e.getX();
ref.y = e.getY();
ref.repaint();
}
}
Does this need to somehow be done in the mouseDragged() method or in the MyFrame class? Is there any way to make an if statement for which method is being called so I could set a color for if(mouseDragged()) or something like that?
On your paint method call g.setColor(color).
Set the color in mouse events to black and red accordingly.
What I'm trying to do is to draw circles and lines.
When the mouse is first pressed, I draw a small circle. Then, I need
to draw a line connecting the original point to the current
position of the mouse. When the mouse is released, the line
remains, but when I click again, everything disappears and I draw a
circle and a line all over again.
This is the code I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Canvas4 extends JComponent implements MouseListener, MouseMotionListener {
//constructor
public Canvas4() {
super();
addMouseListener(this);
addMouseMotionListener(this);
}
//some variables I may or may not use
int pressedX;
int pressedY;
int currentX;
int currentY;
int startDragX;
int startDragY;
int endDragX;
int endDragY;
int mouseReleasedX;
int mouseReleasedY;
//mouse events
public void mouseClicked(MouseEvent event) { }
public void mouseEntered(MouseEvent event) { }
public void mouseExited(MouseEvent event) { }
public void mousePressed(MouseEvent event) {
pressedX = event.getX();
pressedY = event.getY();
drawCircle();
startDragX = pressedX;
startDragY = pressedY;
}
public void mouseReleased(MouseEvent event) {
mouseReleasedX = event.getX();
mouseReleasedY = event.getY();
//repaint() here maybe???
}
//mouse motion events
public void mouseDragged(MouseEvent event) {
System.out.println("You dragged the mouse.");
endDragX = event.getX();
endDragY = event.getY();
drawLine();
}
public void mouseMoved(MouseEvent event) { }
//draw circle when mouse pressed
//this method works fine
public void drawCircle() {
Graphics g1 = this.getGraphics();
g1.setColor(Color.CYAN);
g1.fillOval(pressedX, pressedY, 10, 10);
}
//draw line when mouse dragged
//this is where I need help
public void drawLine() {
Graphics g2 = this.getGraphics();
g2.setColor(Color.RED);
g2.drawLine(pressedX, pressedY, mouseReleasedX, mouseReleasedY);
}
}
Then of course, there's a main method that creates the class object and adds it to a frame and whatnot.
My two specific questions are:
how do I draw a line as it's dragged? The code I have currently only draws a line to the last point of mouse release.
When do I repaint? If I repaint in the drawCircle() method, the circle blinks in and out instead of disappearing on the next click.
If you want to draw circles and lines then you need to keep an ArrayList of Shapes to draw. You would add an Ellipse2D.Double for the circle and a Line2D.Double for the line.
In the mousePressed event you add the Ellipse2D.Double object to the ArrayList, then you set up a temporary Line2D.Double object to contain your line information.
In the mouseDragged event you update Line2D.Double object with the new end point and then invoke repaint().
In the mouseReleased event you add the Line2D.Double object to the ArrayList and clear the variable referencing the Line2D.Double object.
Then in the paintComponent() method you add logic to:
iterate through the ArrayList to paint each Shape.
draw the Line2D.Double object when not null
Check out the Draw On Component example found in Custom Painting Approaches. This will show you the basic concept of this approach.
In the example the ArrayList only contains information on Rectangles so you will need to make it more generic to hold a Shape object. Both Ellispse2D.Double and Line2D.Double implement the Shape interface.
For drawing lines i have this.When you click mouse left you retain a point next click will retain another point making a line between them , and with mouse right you make the line between first point and last point (you can delete this "if (isClosed)" if you dont want)
Another thing : it's not a good precision because pointlocation return a double and drawline need an integer and the cast loses precision.
public class PolygonOnClick extends JPanel implements MouseListener, MouseMotionListener {
ArrayList<Point> points = new ArrayList<>();
static boolean isClosed = false;
PolygonOnClick() {
JFrame frame = new JFrame("Polygon ON CLICK");
frame.addMouseListener(this);
frame.setLocation(80, 50);
frame.setSize(1000, 700);
frame.add(this);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.drawString("Click stanga pentru a incepe a desena , click dreapta pentru a inchide poligonul ", 15, 15);
for (int i = 1; i < points.size(); i++) {
graphics.drawLine((int) points.get(i - 1).getX(), (int) points.get(i - 1).getY(), (int) points.get(i).getX(), (int) points.get(i).getY());
}
if (isClosed) {
graphics.drawLine((int) points.get(points.size() - 1).getX(), (int) points.get(points.size() - 1).getY(), (int) points.get(0).getX(), (int) points.get(0).getY());
}
}
#Override
public void mousePressed(MouseEvent e) {
if (!isClosed) {
if (e.getButton() == MouseEvent.BUTTON1) {
points.add(e.getPoint().getLocation());
}
}
if (e.getButton() == MouseEvent.BUTTON3) {
isClosed = true;
}
repaint();
}
Say I'm in a Java Swing JFrame. I click my mouse. I want to get the location of the mouse click within the GUI. In java, the line
int mouseX = MouseInfo.getPointerInfo().getLocation.x;
Seems to give the location of the mouse on the entire screen. How would I get it's location relative to the GUI?
From MouseListener methods you can do:
#Override
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println(x+","+y);//these co-ords are relative to the component
}
Simply add this to your Component by:
component.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
Reference:
How to Write a Mouse Listener
Take a look at Component.getMousePosition.
Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null. If the Component is not showing on the screen, this method returns null even if the mouse pointer is above the area where the Component would be displayed. If the Component is partially or fully obscured by other Components or native windows, this method returns a non-null value only if the mouse pointer is located above the unobscured part of the Component.
final Point mousePos = component.getMousePosition();
if (mousePos != null) {
final int mouseX = mousePos.x;
final int mouseY = mousePos.y;
...
}
... or, if you use a MouseListener, you may see my original comment...
Try using MouseEvent.getPoint.
The above will return the mouse point relative to the component to which the listener was bound.
public void mouseClicked(final MouseEvent evt) {
final Point pos = evt.getPoint();
final int x = pos.x;
final int y = pos.y;
}
You can add MouseListener to GUI component whose top left pixel should be threated as [0,0] point, and get x and y from MouseEvent
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {// provides empty implementation of all
// MouseListener`s methods, allowing us to
// override only those which interests us
#Override //I override only one method for presentation
public void mousePressed(MouseEvent e) {
System.out.println(e.getX() + "," + e.getY());
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
MouseEvent has methods getX() and getY() that return the position relative to the source component.
Say I'm in a Java Swing JFrame. I click my mouse. I want to get the location of the mouse click within the GUI. In java, the line
int mouseX = MouseInfo.getPointerInfo().getLocation.x;
Seems to give the location of the mouse on the entire screen. How would I get it's location relative to the GUI?
From MouseListener methods you can do:
#Override
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println(x+","+y);//these co-ords are relative to the component
}
Simply add this to your Component by:
component.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
Reference:
How to Write a Mouse Listener
Take a look at Component.getMousePosition.
Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null. If the Component is not showing on the screen, this method returns null even if the mouse pointer is above the area where the Component would be displayed. If the Component is partially or fully obscured by other Components or native windows, this method returns a non-null value only if the mouse pointer is located above the unobscured part of the Component.
final Point mousePos = component.getMousePosition();
if (mousePos != null) {
final int mouseX = mousePos.x;
final int mouseY = mousePos.y;
...
}
... or, if you use a MouseListener, you may see my original comment...
Try using MouseEvent.getPoint.
The above will return the mouse point relative to the component to which the listener was bound.
public void mouseClicked(final MouseEvent evt) {
final Point pos = evt.getPoint();
final int x = pos.x;
final int y = pos.y;
}
You can add MouseListener to GUI component whose top left pixel should be threated as [0,0] point, and get x and y from MouseEvent
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {// provides empty implementation of all
// MouseListener`s methods, allowing us to
// override only those which interests us
#Override //I override only one method for presentation
public void mousePressed(MouseEvent e) {
System.out.println(e.getX() + "," + e.getY());
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
MouseEvent has methods getX() and getY() that return the position relative to the source component.
Say I'm in a Java Swing JFrame. I click my mouse. I want to get the location of the mouse click within the GUI. In java, the line
int mouseX = MouseInfo.getPointerInfo().getLocation.x;
Seems to give the location of the mouse on the entire screen. How would I get it's location relative to the GUI?
From MouseListener methods you can do:
#Override
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println(x+","+y);//these co-ords are relative to the component
}
Simply add this to your Component by:
component.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
Reference:
How to Write a Mouse Listener
Take a look at Component.getMousePosition.
Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null. If the Component is not showing on the screen, this method returns null even if the mouse pointer is above the area where the Component would be displayed. If the Component is partially or fully obscured by other Components or native windows, this method returns a non-null value only if the mouse pointer is located above the unobscured part of the Component.
final Point mousePos = component.getMousePosition();
if (mousePos != null) {
final int mouseX = mousePos.x;
final int mouseY = mousePos.y;
...
}
... or, if you use a MouseListener, you may see my original comment...
Try using MouseEvent.getPoint.
The above will return the mouse point relative to the component to which the listener was bound.
public void mouseClicked(final MouseEvent evt) {
final Point pos = evt.getPoint();
final int x = pos.x;
final int y = pos.y;
}
You can add MouseListener to GUI component whose top left pixel should be threated as [0,0] point, and get x and y from MouseEvent
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {// provides empty implementation of all
// MouseListener`s methods, allowing us to
// override only those which interests us
#Override //I override only one method for presentation
public void mousePressed(MouseEvent e) {
System.out.println(e.getX() + "," + e.getY());
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
MouseEvent has methods getX() and getY() that return the position relative to the source component.