reo*_*eox 5 java swing jpanel layout-manager
我想在一个圆圈中放置10个JPanel.每个小组的大小相同,两个小组之间的长度应相同.因此,我认为最简单的方法是获取null-Layout并通过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;
}
Run Code Online (Sandbox Code Playgroud)
但那不起作用!有些项目在圈子上,其中一些是像素关闭...我有一个不知道为什么?!我也找不到可以为我做的那个LayoutManager,那该怎么办?
虽然X-Zero给出了正确答案(他的帖子中有1+),但我创建了一个SSCCE:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
public class PanelsOnCircle extends JPanel {
private static final int RADIUS = 100;
private static final int GAP = 20;
private static final int PREF_W = 2 * RADIUS + 2 * GAP;
private static final int PREF_H = PREF_W;
private static final int SLICES = 10;
private static final int SIDE = 4;
public PanelsOnCircle() {
JPanel panel = new JPanel(null);
for (int i = 0; i < SLICES; i++) {
double phi = (i * Math.PI * 2) / SLICES;
JPanel smallPanel = new JPanel();
smallPanel.setBackground(Color.red);
int x = (int) (RADIUS * Math.sin(phi) + RADIUS - SIDE / 2) + GAP;
int y = (int) (RADIUS * Math.cos(phi) + RADIUS - SIDE / 2) + GAP;
smallPanel.setBounds(x, y, SIDE, SIDE);
panel.add(smallPanel);
}
setLayout(new BorderLayout());
add(panel);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
PanelsOnCircle mainPanel = new PanelsOnCircle();
JFrame frame = new JFrame("PanelsOnCircle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
从他第一次开始就接受X-Zero的回答.
你的代码很好,但是你错过了一条非常重要的信息 - 三角函数预计弧度的 角度而不是 度.
包含phiin 的评估Math.toRadians(double),您将获得您期望的布局.
(旁注,我一直在考虑如何做这样的事情,谢谢你的例子)
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |