Search code examples
javaobjectgraphicsmousearea

How to move Area class object in Java Graphics2D


I'm working with Graphics2D(java)

I'm trying move a random shape with mouse drag.

This random shape is stored in Area object of java.awt.geom.Area class.

I know how to select that area object, I just need to figure out how to actually move it to the new coordinates.

Shapes like ellipse and rectangle can be easily moved but how to move shapes like polygon or shapes that contain curve and no specific predefined structure.


Solution

  • In order to draw a rectangle using the Graphics class, you need the origin point and the width and height.

    In order to draw an ellipse using the Graphics class, you need the origin point and the width and height.

    Each of these simple figures is made up of an origin point and the dimensions of the figure.

    Similarly, for any complex shape, you need an origin point. It's the origin point that "moves" when you move the shape with a mouse drag. In other words, the origin of the mouse move corresponds with the origin of the figure. As the mouse moves to new X and y coordinates, your origin moves to new x and y coordinates.

    Let's say a rectangle has an origin of 10, 10. Let's say the origin of the mouse drag is 30, 30. As the mouse moves to new x and y coordinates, you change the origin of the rectangle. In this example, when the mouse has moved to 40, 40, the origin of the rectangle becomes 20, 20.

    The rectangle and ellipse already have a draw method in the Graphics class. You'll probably have to write your own draw method for the complex shape.