Brian
Brian

Reputation: 11

How to get exact position of a Canvas (Java)

In my code, I use mouse coordinates to interact with the program. From there, something must be drawn at the mouse's location. However, the getX()/getY() methods for the Canvas return the values of the window holding the Canvas, but when I go to draw, (0,0) is located slightly to the right and below (past the bars) the top left of the window, resulting in being approximately 30 pixels off of the correct location. Is there a way to reconcile the differences, or should I simply fullscreen the window or use some other method to sidestep the problem altogether?

Upvotes: 1

Views: 3964

Answers (2)

Viviana
Viviana

Reputation: 11

Using the getX()/getY() methods but inside a mosueDragged/click listener, working with an event.

Check this example (the parameters):

protected Graphics2D g2;
protected int xStart;
protected int xEnd;
protected int yStart;
protected int yEnd;

//On the parameters, there is the MouseEvent
public void startDrawing(JPanel canvas, MouseEvent evt) {
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    if (g2 == null)

    {
    g2 = (Graphics2D) canvas.getGraphics();
    }

    xStart = evt.getX();
    yStart = evt.getY();
    xEnd = evt.getX();
    yEnd = evt.getY();
}

Then the method is used, on a Mouse pressed event:

 private void canvasMousePressed(java.awt.event.MouseEvent evt) {                                    

    if(penClicked) {
        (penContainer.get(penCount)).startDrawing(canvas, evt);
        (penContainer.get(penCount)).setColor(color);
        penContainer.add(new Pen());
        penCount++;
  }

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328764

I guess you registered the MouseListener and MouseMotionListener to the window. Register them for the Canvas and you get coordinates relative to this widget. See this sample code.

Upvotes: 4

Related Questions