I'm trying to get the mouse's position within a panel, as in the top left of the panel = x/y 0,0.
What I have at the minute gives the position on the entire screen, so depending on where the panel (which is in a frame) is on the screen, the coordinates are different. I guess you could add to the x/y co-ordinates to account for this, but this seems like a messy solution. Can anyone help?
Here's the mouseListener I'm using, which has been added to the panel.
private class MouseListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
// Finds the location of the mouse
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
// Gets the x -> and y co-ordinates
int x = (int) b.getX();
int y = (int) b.getY();
System.out.println("Mouse x: " + x);
System.out.println("Mouse y: " + y);
// Determines which tile the click occured on
int xTile = x/tileSize;
int yTile = y/tileSize;
System.out.println("X Tile: " + xTile);
System.out.println("Y Tile: " + yTile);
}
}
See MouseEvent.getPoint().
Returns the x,y position of the event relative to the source component.
You can use MouseEvent.getX() and MouseEvent.getY() to get the relative co-ordinates of X & Y respectively.
int relativeX = e.getX();
int relativeY = e.getY();
...
Related
I have written some code to implement a drag to zoom (i.e. draw a rectangle with the mouse and then zoom into this area so it fills the container) on a JPanel. However, before I wrote this into the Listener, I had a "mouseClicked" method, which is still there. This method performed a different function, simply returning the coords of the click.
Unfortunately, I mistakenly implemented the zoom function using MousePressed, which thus runs at the same time as the mouseClicked event. This means that when I click the mouse to get the coordinates, it also zooms in on a very small rectangle. Is there anyway to change this?
Thanks in advance for any suggestions, and please let me know if you need anything clarifying!
Here is the listener class:
class panelClickListener extends MouseAdapter implements MouseMotionListener {
JLabel toShowCoords, rangeLabel;
juliaPanel panelJulia;
mandPanel panelMand;
int startX, startY, currentX, currentY;
boolean dragging;
ComplexNumber startRange, endRange;
public panelClickListener(JLabel toShowCoordsIn, juliaPanel panelJuliaIn, mandPanel panelMandIn, JLabel rangeLabelIn) {
toShowCoords = toShowCoordsIn;
panelJulia = panelJuliaIn;
panelMand = panelMandIn;
rangeLabel = rangeLabelIn;
}
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
userSelectedPoint = pointsToDrawOn[x][y];
toShowCoords.setText("Number Selected: " + userSelectedPoint.getReal() + " , " + userSelectedPoint.getImaginary());
panelJulia.setFixedNumber(pointsToDrawOn[x][y]);
panelJulia.repaint();
}
public void mousePressed(MouseEvent event) {
Point point = event.getPoint();
startX = point.x;
startY = point.y;
dragging = true;
}
public void mouseReleased(MouseEvent event) {
dragging = false;
startRange = pointsToDrawOn[startX][startY];
endRange = pointsToDrawOn[currentX][currentY];
maxVal = endRange;
minVal = startRange;
rangeLabel.setText("Real axis: " + minVal.getReal() + "," + maxVal.getReal() + " - Imaginary axis: " + minVal.getImaginary() + "," + maxVal.getImaginary());
populatePointArray();
panelMand.repaint();
}
public void mouseDragged(MouseEvent event) {
Point p = event.getPoint();
currentX = p.x;
currentY = p.y;
}
}
dragging should only be set to true when mouseDragged is called, then when mouseReleased is called, you need to check to see if dragging is true before processing the zoom
There's some theory to go with that, mouseClicked will only be called if the point of the mouse is the same for mousePressed and mouseReleased.
So in a click operation you can expect mousePressed, mouseReleased and mouseClicked to be called (I believe in that order, but you'd better test it).
In a drag operation, you can expect mousePressed, mouseDragged and mouseReleased to be called
I know with the robot class I can move my mouse to an (x,y) coordinate but is there a way to return this (x,y) coordinate that my mouse is currently hovering over? Or possibly a way to see the (x,y) coordinate that I have last clicked.
I'm using the returns to map out a specific order of coordinates that need to be clicked and I don't want to guess which pixel it is on a 4k screen.
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
Robot r = new Robot();
r.mouseMove(x + 100 , y + 100 );
I am currently making an AWT game engine, a simple one just getting conversant with AWT. I am currently working on the physics of the game. I am trying to implement a function that moves the entity forward on it's direction from the north line, or the x axis. This is the code I am using to achieve this:
public void move(double d) {
oldX = x;
oldY = y;
double angle = Math.toRadians(getDirection());
int dx = (int) Math.round(Math.cos(angle) * d);
int dy = (int) Math.round(Math.sin(angle) * d);
setLocation(x + dx, y + dy);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("direction = " + angle);
System.out.println("----------");
}
and I call this code in this snippet:
for(Entity e : entities) {
if(!e.getLevel().equals(this)) {
return;
}
e.move(3); //testing the code atm
e.changeDirection(e.getDirection() + 3);
}
The problem is that it won't go in a circle, or oval trajectory as I would expect when you have a vector forward (move(int i)) method and changing the direction by 3 every tick as the force acting on the vector, or gravity if we were talking about Earth orbiting objects. This is the expected behaviour.
However, this is what actually happens:
gif demonstration - imgur
Could you tell me why this behavior is occurring and how I could solve this? Thanks
The actual problem, as #harold says, is not the maths but the rendering. Here is what the fixed code to render the 2d entity looks like:
for(Entity e : entities) {
AffineTransform trans = new AffineTransform();
trans.setTransform(identity);
Point mouse = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointToScreen(mouse, this);
trans.rotate(Math.toRadians(e.getDirection()), e.getX(), e.getY());
//changed from trans.rotate(Me.getDirection(), e.getX() + e.image.getWidth(null)/2, e.getY() + e.image.getHeight(null)/2);
trans.translate(e.getX(), e.getY());
g2d.drawImage(e.getImage(), trans, this);
}
I use JPanel to draw a square on the screen.
When I use MouseDragged it works fine and goes wherever I want, almost. Each time I click on the square, the square automatically moves and the top left corner goes right under the mouse.
How should I do so that the square doesn't replace itself and stays right under the mouse ?
Thanks for any help.
Keep an account of the difference between top-left coordinates of Component which you are
moving and mousePressed location.
And when you get new position, just subtract that difference to it.
Here I have tried to explain it through coding. Let myJPanel be the component you want to
move. Then here is the MouseAdapter that can work for you. New position is stored in
newPosition variable.
new MouseAdapter(){
int diffx = 0, diffy = 0;
public void mousePressed(MouseEvent e) {
Point topLeft = myJPanel.getLocation();
Point mouseDn = e.getPoint();
diffx = mouseDn.x - topLeft.x;
diffy = mouseDn.y - topLeft.y;
}
public void mouseDragged(MouseEvent e) {
Point mouseDr = e.getPoint();
int newX = mouseDr.x - diffx;
int newY = mouseDr.y - diffy;
Point newPosition = new Point(newX, newY);
}
};
I have a Java swing application where I can draw hot spots. I am allowing user to draw Rectangle , Polygon and Circle.
For Circle I am using Ellipse2D
Ellipse2D.Double ellipseDouble = new Ellipse2D.Double(x,y,width,height);
g.draw(ellipseDouble);
Above works fine and it does draw an ellipse/circle.
Now the problems when I want the region to be used in HTML Image map.
Html Image map doesn't support Ellipse so I was thinking to use polygon for Ellipse2D but really don't know how would I convert it.
Does anyone know how would I go about it converting an Ellipse2D to Polygon ponits?
Use FlatteningPathIterator.
See e.g. http://java-sl.com/tip_flatteningpathiterator_moving_shape.html where point moves following custom Shape.
You can get list of Points and create Polygon.
Maybe someone will find this one useful: this is pdfbox ellipse or circle (width=height) draw function inside rectangle, it make ellipse as polygon initially to draw.
Code based on math function of ellipse at poin [0 , 0]: x^2/a^2 + y^2/b^2 = 1
private PdfBoxPoligon draw_Ellipse_or_Circle_as_poligon_with_PDFBOX (
PDPageContentStream content, float bottomLeftX, float bottomLeftY,
float width, float height, boolean draw) throws IOException {
PdfBoxPoligon result = new PdfBoxPoligon();
float a = width/2;
float b = height/2;
int points = (int) (a*b/20);
if (DEBUG) {
System.out.println("points=" + points);
}
//top arc
for (float x = -a; x < a; x = x + a / points) {
result.x.add(bottomLeftX + a + x);
float y = (float) Math.sqrt((1-(x*x)/(a*a))*(b*b));
result.y.add(bottomLeftY+b+y);
}
//bottom arc
for (float x = a; x >= -a; x = x - a / points) {
result.x.add(bottomLeftX + a + x);
float y = -(float) Math.sqrt((1-(x*x)/(a*a))*(b*b));
result.y.add(bottomLeftY+b+y);
}
result.x.add(result.x.get(0));
result.y.add(result.y.get(0));
if (draw) {
for (int i=1; i < result.x.size(); i++) {
content.addLine(result.x.get(i-1), result.y.get(i-1), result.x.get(i), result.y.get(i));
}
}
return result;
}