0

I understand how to use MouseMotionListener but I can't get the parameters right for drawing a rectangle and an oval.

This is my attempt at a rectangle, but the problem is if go to the left from the start point, the rectangle gets filled.

public void draw(Graphics g) {

    g.drawRect((int)startPoint.getX(), (int)startPoint.getY(),(int)controlPoint.getX() - (int)startPoint.getX(),    (int) controlPoint.getY() - (int)startPoint.getY());

}

This is my method for a circle, this seems to work fine. But i cannot alter it for it to form an oval.

public void draw(Graphics g) {
    g.drawOval((int)startPoint.getX() - (int)controlPoint.distance(startPoint),((int)startPoint.getY() - (int)controlPoint.distance(startPoint)),
            (int)controlPoint.distance(startPoint)*2,(int)controlPoint.distance(startPoint)*2);
}

The mousePressed must be the center(startPoint) and the drag should be the radius for an oval.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Pixelidiot
  • 47
  • 1
  • 7
  • Both `drawRect` and `drawOval` expect `x, y, width, height`...It's possible that your start x or start y could be less then you end x or end y positions. So you need to compensate for that... – MadProgrammer Aug 21 '14 at 05:00

2 Answers2

0
  • Both Graphics#drawRect and Graphics#drawOval expect the parameters to mean x, y, width, height, not x1, y1, x2, y2...
  • Your start points may be greater than your end points, resulting in either or both the width and/or height been negative values (based on width = x1 - x2). The Graphics API doesn't like negative values very much. You will need to take this into consideration when calculating the starting points and size.

The crust of the problem can be solved using something like...

int minX = Math.min(currentX, startX);
int minY = Math.min(currentY, startY);
int maxX = Math.max(currentX, startX);
int maxY = Math.max(currentY, startY);

int x = minX;
int y = minY;
int width = maxX - minX;
int height = maxX - minX;

Take a look at java draws rectangle one way not both for a working example...

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Let me for brevity change the variable names from startPoint to sp and from controlPoint to cp, then these changes to your code should do the trick:

int minX = Math.min(sp.x, sp.y);
int minY = Math.min(sp.x, sp.y);
int width = Math.abs(cp.x - sp.x);
int height = Math.abs(cp.y - sp.y);

g.drawRect(minX, minY, width, height);
g.drawOval(minX, minY, width, height);

The reason is that those methods should receive the top-left corner coordinates, as well as the width and height of the bounding box of the rect/oval being drawn.

ethanfar
  • 3,733
  • 24
  • 43