Setting the pivot point of a JPanel to its center

2019-08-28 12:47发布

问题:

I am building a Java application that is going to feature two circles of random sizes that need to be clicked by the user. The time between the click on the first and the second circle is going to be measured. Unfortunately, since I am new to Java so things have been slow for me. Currently I have my application draw circles and measure time between clicks using System.nanoTime() but now I am running into a problem.

Because the circles need to be a fixed distance away from eachother I want to use the center of the circles as the origin points. So basically I want to be able to provide coordinates for the circle so that the center of the circle should be at those coordinates. The distance between the circles then describes the distance between the centers. My circle currently is embedded into a JPanel but if I set the JPanel's position it moves the top left to that position.

Of course I have done some searching read that I may need to play around with either AffineTransform or Graphics2D.translate() which I have tried in paintComponent() but this got a bit confusing so then I tried to override setlocation and subtract the radius from the position. It sort of works but it is not the most clean solution. Can aonyone give me some pointers on how to do this?

Thanks in advance.

回答1:

If I understand the problem statement, all such pairs of circles will lie on opposite sides of a circle centered in the enclosing panel, as shown here. Simply choose a random 0 ≤ θ < π and find its opposite at π - θ. Note how the example's rendering scales as the panel is resized.

As an aside, the example uses setPreferredSize() to establish the dimensions of the drawing panel, but you may want to override getPreferredSize() instead.

Addendum: The example uses fillOval() to render the circles, but you can use draw() with any desired Shape; the latter provides several contains() methods suitable for hit testing, as mentioned here.



回答2:

You have the coordinates for the two center for the circle (x1, y1) and (x2, y2). The size of the radius is random. Once you have the radius of the two, r1 and r2, simply position them at (x1-r1, y1-r1) and (x2-r2, y2-r2).

You can use java.awt.Point to represent the center, and use

center.translate(-radius, -radius)

and use the new translated value as position for the drawing.

Maybe you think it is not a clean solution, but why not? Everything in Java is painted by giving the top left corner for the position, so is the use of the center that is not clean :). To calculate the left top position by doing -radius is clean :)