Getting the coordinates of the panel - java

Using mouseevents, I am able to get the x and y coordinates of the frame, yet I am unable to get the x and y coordinates of the panel. The below codes are me getting the x and y coordinates of the frame.
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
text = Integer.toString(x) +","+Integer.toString(y);
Frame.frame.repaint();
}
The below codes are me trying to get the x and y coordinates of the panel, but it's painting out 0's instead. Paint.paint is the name of my jpanel. I don't know what I'm doing wrong. Please help if you can.
public void mouseMoved(MouseEvent e) {
x = Paint.paint.getX();
y = Paint.paint.getY();
text = Integer.toString(x) +","+Integer.toString(y);
Frame.frame.repaint();
}

If I understand right, your MouseListener is registered with the JFrame, and you wish to get the x/y relative to a JPanel contained within the JFrame. The x and y within the MouseEvent refer to the Component in which the MouseListener was registered. If you have a MouseListener registered on a Parent container, and which to get the coordinates of the MouseEvent relative to a child Component, you can using SwingUtilities to convert the coordinates
public void mousePressed(MouseEvent e){
Point childCoordinate = SwingUtilities.convertPoint(parent, e.getPoint(), child);
}

Related

How does the drawing guide in this java paint program work?

I'm currently doing a paint program where we are drawing squares where they must draw as the user drags the mouse.
My professor taught it to us using the graphics XOR mode.
I found this code and it looks much more efficient.
I am confused as to how the guide works, the way its written to me looks like as they are dragging the mouse. It would just create a bunch of different rectangles and they would all stay on the screen.
How is it that the rectangle is continuously updating to the users mouse but not staying on the screen?
Is it because the shape is not being added to an ArrayList?
public DrawingBoard() {
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// When the mouse is pressed get x & y position
drawStart = new Point(e.getX(), e.getY());
drawEnd = drawStart;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// Create a shape using the starting x & y
// and finishing x & y positions
Shape aShape = drawRectangle(drawStart.x, drawStart.y, e.getX(), e.getY());
// Add shapes, fills and colors to there ArrayLists
shapes.add(aShape);
shapeFill.add(fillColor);
shapeStroke.add(strokeColor);
drawStart = null;
drawEnd = null;
// repaint the drawing area
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
// Get the final x & y position after the mouse is dragged
drawEnd = new Point(e.getX(), e.getY());
repaint();
}
});
}
public void paint(Graphics g) {
// Class used to define the shapes to be drawn
Graphics2D graphSettings = (Graphics2D) g;
// Antialiasing cleans up the jagged lines and defines rendering rules
graphSettings.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Defines the line width of the stroke
graphSettings.setStroke(new BasicStroke(2));
// Iterators created to cycle through strokes and fills
Iterator<Color> strokeCounter = shapeStroke.iterator();
Iterator<Color> fillCounter = shapeFill.iterator();
// Eliminates transparent setting below
graphSettings.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
for (Shape s : shapes) {
// Grabs the next stroke from the color arraylist
graphSettings.setPaint(strokeCounter.next());
graphSettings.draw(s);
// Grabs the next fill from the color arraylist
graphSettings.setPaint(fillCounter.next());
graphSettings.fill(s);
}
// Guide shape used for drawing
if (drawStart != null && drawEnd != null) {
// Makes the guide shape transparent
graphSettings.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.40f));
// Make guide shape gray for professional look
graphSettings.setPaint(Color.LIGHT_GRAY);
// Create a new rectangle using x & y coordinates
Shape aShape = drawRectangle(drawStart.x, drawStart.y, drawEnd.x, drawEnd.y);
graphSettings.draw(aShape);
}
}
The code will store all the rectangles user created. If you want one rectangle in the screen, you can draw the rectangle without saving it in the arraylist. delete all codes which are related to the arraylist.

Converting 720p screen to relative point on larger display

I'm trying to create a remote desktop access tool in Java (more of an experiment than anything really), but i'm having trouble converting the point in which is clicked to a location on the main screen. Let me explain.
Here's an example of how the tool looks (for now).
The screen capture window is 1280x720, and the actual screens vary in size, how can I get the location of where the mouse is and change it to the same location on the main screen?
e.g. if I click on the apple logo on the screen capture window, it should move my mouse and click on the apple logo on the main screen. I just can't figure out how to get the point in the window, and translate it to the same point on the main screen!
EDIT: Here is what i'm trying to do atm:
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
PacketMoveMouse packetMoveMouse = new PacketMoveMouse(address, e.getXOnScreen(), e.getYOnScreen());
sendPacket(address, packetMoveMouse);
}
#Override
public void mousePressed(MouseEvent e) {
Point point = this.getPoint(e.getPoint());
PacketClickMouse packetClickMouse = new PacketClickMouse(address, point.getX(), point.getY(), e.getButton());
sendPacket(address, packetClickMouse);
}
private Point getPoint(Point point) {
SwingUtilities.convertPointFromScreen(point, panel);
return point;
}
};
I also tried without converting the point, i was just trying various things. It moves the mouse correctly, but to the wrong point.
I also tried to convert it to a point on the main screen using some basic math, but i think my logic flawed, here is what i tried:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
int x = ((PacketMoveMouse) packet).getX();
int y = ((PacketMoveMouse) packet).getY();
double xRatio = (screenRect.getWidth() / 1280);
double yRatio = (screenRect.getHeight() / 720);
Robot robot = new Robot();
robot.mouseMove((int) ((x * xRatio)), (int) ((y * yRatio)));
This is when i just send the regular point to the client then change to to a relative point once it's received. The display screen of the client is 1280x720 currently.
To get your mouse CURRENT coordinates
int mouseX;
int mouseY;
#Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}

Transform mouse listener coordinates into chart coordinates

I want to set dots in my app with mouse click. I use JFreeChart and use in ChartPanel mouse listener. This is look like this:
panel.addChartMouseListener(new ThisMouseListener());
and my mouse listener ThisMouseListener() (it is not finished):
class ThisMouseListener implements ChartMouseListener{
#Override
public void chartMouseClicked(ChartMouseEvent event) {
int x = event.getTrigger().getX();
int y = event.getTrigger().getY();
System.out.println("X :" + x + " Y : " + y);
ChartEntity entity = event.getEntity();
if(entity != null && (entity instanceof XYItemEntity)){
XYItemEntity item = (XYItemEntity)entity;
}
new JOptionPane().showMessageDialog(null, "Hello", "Mouse Clicked event", JOptionPane.OK_OPTION);
}
#Override
public void chartMouseMoved(ChartMouseEvent arg0) {
// TODO Auto-generated method stub
}
}
but this mouse listener returns me my panel coordinates and I want to get coordinates from my chart. May be I must use listener with other object? or I can transform coordinates with some method?
You added the listener to the panel. Therefore when you click the mouse you receive coordinates relative to the panel - which is the source of the event. You need to add this listener to the chart instead.
Other possibility is to get coordinates of the chart in respect to panel and subtract them from x and y.
Point p = chart.getLocation();
int px = p.getX();
int py = p.getY();
x = x-px; // x from event
y = y-py; // y from event
// x and y are now coordinates in respect to the chart
if(x<0 || y<0 || x>chart.getWidth() || y>chart.getHeight()) // the click was outside of the chart
else // the click happened within boundaries of the chart and
If the panel is the container of the chart component your solution might look something like the above one. Note that these coordinates will be coordinates in respect to left top corner of the chart.
Get the x,y coordinates in your graph space via
double x = event.getChart().getXYPlot().getDomainCrosshairValue();
double y = event.getChart().getXYPlot().getRangeCrosshairValue();
One major PROBLEM: I find that JFreeChart doesn't update these values until after my ChartMouseEvent handler is called; each time through I get the previous values. You can look at XYPlot.handleClick(x,y,info) for details to get the current values in your handler.
You have to obtain a reference to the ChartPanel, rredraw it and only after that you can get a correct X,Y coordinates from the Plot. To do so, you have to place coordinate retrieval on the awt queue and not call it directly. Below is an example that worked for me (for X coordinate only)
#Override
public void chartMouseClicked(ChartMouseEvent cme) {
final ChartMouseEvent cmeLocal = cme;
ChartPanel hostChartPanel = (ChartPanel) cme.getTrigger().getComponent();
if (null != hostChartPanel) {
//Crosshair values are not valid until after the chart has been updated
//that is why call repaint() now and post Crosshair value retrieval on the
//awt thread queue to get them when repaint() is finished
hostChartPanel.repaint();
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFreeChart chart = cmeLocal.getChart();
XYPlot plot = chart.getXYPlot();
double crossHairX = plot.getDomainCrosshairValue();
JOptionPane.showMessageDialog(null, Double.toString(crossHairX), "X-Value", JOptionPane.OK_OPTION);
}
});
}
}

Java mapkit viewportbounds

I am using the jxmapkit to show a map in a java frame.
Now i am trying to translate a click x,y position into Lat, Long.
This is what I have so far:
public void mouseClicked(MouseEvent e)
{
Point point = e.getPoint();
JXMapViewer map = mainMap.getMainMap();
Rectangle bounds = map.getViewportBounds();
int x = (int)(point.getX() - bounds.getX());
int y = (int)(point.getY() - bounds.getY());
GeoPosition mappos = map.getTileFactory().pixelToGeo(new Point(x,y), map.getZoom());
But the bounds x and y are too big 282723 and 205680 so the translation is obviously failing.
Does
Rectangle bounds = map.getViewportBounds();
work or am I doing something wrong?
are you tried to put that into JScrollPane and then just move with Rectangle to Visible ViewPort, I think that's job for that ...

Difficulty understanding Java MouseEvent

I'm doing these iTunes Stanford classes, and I've been learning beginning Java. Things are going great, but they recently introduced events-and specifically MouseEvents. I've been reading the chapters in the book, and pouring through the example code, and something is just not clicking right for me...it's always that asynchronous stuff that gives me trouble :-D
Earlier, some people mentioned it was important that I mention that the "addMouseListener" is a class in the Graphics import. As far as I can tell, that just adds a blanket mouse listener to the canvas.
I'm still real new to this, so I may not be describing things as well as I should.
This is a piece of code that I have been trying to simplify in order to better understand it. Currently, it will build a red rectangle, and I can click on it and drag it along the x axis. Great!!!
import java.awt.*;
import java.awt.event.*;
import acm.graphics.*;
import acm.program.*;
/** This class displays a mouse-draggable rectangle and oval */
public class DragObject extends GraphicsProgram {
/* Build a rectangle */
public void run() {
GRect rect = new GRect(100, 100, 150, 100);
rect.setFilled(true);
rect.setColor(Color.RED);
add(rect);
addMouseListeners();
}
/** Called on mouse press to record the coordinates of the click */
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
gobj = getElementAt(lastX, lastY);
}
/** Called on mouse drag to reposition the object */
public void mouseDragged(MouseEvent e) {
if((lastX) > 100){
gobj.move(e.getX() - lastX, 0);
lastX = e.getX();
lastY = e.getY();
}
}
/** Called on mouse click to move this object to the front */
public void mouseClicked(MouseEvent e) {
if (gobj != null) gobj.sendToFront();
}
/* Instance variables */
private GObject gobj; /* The object being dragged */
private double lastX; /* The last mouse X position */
private double lastY; /* The last mouse Y position */
}
If I drag the mouse off the canvas, I want the rectangle to stay within the canvas, and not move off it (the same behavior that a horizontal scroll bar would do if you moved beyond the scroll area with the mouse button still clicked). How can I do that?
I've been trying something along these lines, but it's not working right:
if ( ( lastX > (getWidth() - PADDLE_WIDTH) ) || ( lastX < PADDLE_WIDTH ) ) {
gobj.move(0, 0);
} else {
gobj.move(e.getX() - lastX, 0);
}
Your code is moving the rectangle relative to the last position of the mouse. This works fine when you are simply moving things, but for your needs when you want it to stop at the borders, you need to use absolute positioning.
// When the mouse is pressed, calculate the offset between the mouse and the rectangle
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
gobj = getElementAt(lastX, lastY);
}
public void mouseDragged(MouseEvent e) {
double newX;
// Assuming you can get the absolute X position of the object.
newX = gobj.getX() + e.getX() - lastX;
// Limit the range to fall within your canvas. Adjust for your paddle width as necessary.
newX = Math.max( 0, Math.min( newX, getWidth() ) );
// Set the new position of the paddle, assuming you can set the absolute position.
gobj.setX( newX );
lastX = e.getX();
lastY = e.getY();
}
}
This may not be quite what you want because as soon as you go off the edge, the object will stop moving, but then once you move back toward the canvas, your paddle will move immediately instead of waiting for the mouse to reach the same relative position to the paddle at which it started.
You can probably experiment to get it to do what you want.
In order to do this you will need to know the width of the Canvas object, i'm sure there will be a method that will provide this value. You can then check the current x location of the MouseEvent against the width of the canvas, and not increment the x coordinates of the shape object once you are past the width of the canvas. Depending on how much of the shape you want to remain in the canvas, you may need to take into account the width of the shape object as well.
One thing that helps me when dealing w/ animation and moving objects in a gui is drawing out a few scenarios on paper, and noting how the coordinates change.

Categories

Resources