将JPanel的枢轴点设置为其中心 [英] Setting the pivot point of a JPanel to its center

查看:208
本文介绍了将JPanel的枢轴点设置为其中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Java应用程序,它将具有两个需要用户单击的随机大小的圆圈.单击第一个和第二个圆圈之间的时间将被测量.不幸的是,由于我是Java的新手,所以对我来说事情进展缓慢.目前,我的应用程序使用System.nanoTime()绘制圆圈并测量两次点击之间的时间,但是现在我遇到了问题.

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.

因为圆与彼此之间必须保持固定的距离,所以我想将圆的中心用作原点.因此,基本上,我希望能够为圆提供坐标,以使圆的中心位于这些坐标处.然后,圆之间的距离描述了中心之间的距离.我的圈子当前已嵌入到JPanel中,但是如果我设置了JPanel的位置,则它将左上角移到该位置.

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.

当然,我已经做了一些搜索阅读,可能需要在paintComponent()中尝试使用AffineTransform或Graphics2D.translate(),但这有点令人困惑,因此我尝试覆盖setlocation并减去位置的半径.它可以工作,但不是最干净的解决方案.可以给我一些提示吗?

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?

谢谢.

推荐答案

如果我理解问题陈述,所有这些成对的圆将位于以封闭面板为中心的圆的相对两侧,如

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.

顺便说一句,该示例使用setPreferredSize()建立绘图面板的尺寸,但是您可能需要覆盖 .

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

附录:示例使用fillOval()绘制圆,但是您可以将draw()与任何所需的颜色一起使用. Shape;后者提供了几种适用于命中测试的contains()方法,如此处所述.

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.

这篇关于将JPanel的枢轴点设置为其中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆