Skip to content
Advertisement

Center shape defined in Cartesian coordinates in JPanel

I have a shape (triangle for example) defined in Cartesian coordinates and I’d like to translate the shape to the center of a JPanel. I’ve been able to translate about the JPanel’s 0,0 orientation, but I can’t figure out how to center based on the JPanel’s width and height. I’d like to be able to center any shape defined by a bounding rectangle.

JavaScript

This puts the triangle upside down (not desired) in the JPanel’s upper left corner, somewhat expected. So in order to translate the triangle to the center, it should be around half of the panels width and height? I then change the above to:

JavaScript

Now the triangle is in the lower right of the JPanel, so half of the width and height is too much. I then randomly tried /4 and it is close, but not exact and not mathematically correct or at least doesn’t make sense. It also doesn’t work when the JPanel isn’t square.

Advertisement

Answer

So, problems…

  • Some coordinates are negative (you’ve compensated for those already)
  • The shape’s origin is not 0x0, so it’s offset

So, in addition to the “negative coordinates” transformation, you also need to apply a “offset” translation, so that the origin point of the shape becomes 0x0, something like…

JavaScript

Which can produce something like…

enter image description here

(nb: I also rendered the shape’s bounds as a secondary check)

Now, obviously, this is just focused on centring around the shape bounds and you may need to do some additional compensations, but this should give you a starting point.

Runnable example…

JavaScript

nb: I choose to modify the shape within the context of the paint path, you could apply the transformations to the shape itself, but that would depend on your requirements, ie: does anything else depend on the original shapes position or not

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement