将组件放置在圆中
我想将 10 个 JPanel 放置在一个圆圈中。每个面板的尺寸相同,两个面板之间的长度也应相同。所以我想到的最简单的方法是获取一个空布局并通过极坐标手动计算边界框:
JPanel panel = new JPanel(null);
int r = 100;
int phi = 90;
for (int i = 0; i < 10; i++) {
JPanel x = new JPanel();
x.setBackground(Color.red);
x.setBounds((int) (r * Math.sin(phi)) + 100, (int) (r * Math.cos(phi)) + 100, 4, 4);
panel.add(x);
phi = (phi + 36) % 360;
}
但这不起作用!有些项目在圆圈上,有些则偏离像素...我完全不知道为什么?! 我也找不到可以为我做到这一点的 LayoutManager,那么该怎么办呢?
I want to position 10 JPanels in a Circle. Every Panel has the same size and the length between two Panels should be the same. So the easiest way i thought is to grab a null-Layout and compute the bounding box by hand via polarcoordiantes:
JPanel panel = new JPanel(null);
int r = 100;
int phi = 90;
for (int i = 0; i < 10; i++) {
JPanel x = new JPanel();
x.setBackground(Color.red);
x.setBounds((int) (r * Math.sin(phi)) + 100, (int) (r * Math.cos(phi)) + 100, 4, 4);
panel.add(x);
phi = (phi + 36) % 360;
}
But that doesnt work! Some items are on the circle, some of them are pixels off... i have a bsolutly no idea why?!
I also cant find a LayoutManager that can do that for me, so what to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 X-Zero 给出正确答案(他的帖子为 1+)时,我创建了一个 SSCCE:
While X-Zero was giving the correct answer (1+ to his post), I created an SSCCE:
您的代码很好,但您错过了一条非常重要的信息 - 三角函数期望角度以弧度 而不是 度为单位。
将
phi
的计算包含在Math.toRadians(double)
中,您将获得您期望的布局。(顺便说一句,我一直在考虑如何做这样的事情,谢谢你的例子)
Your code is good, but you've missed one very important piece of information - the trigonometric functions expect angles in radians not degrees.
Wrap the evaluation of
phi
inMath.toRadians(double)
, and you'll get the layout you expect.(On a side note, I've been thinking about how to do something like this, thanks for the example)