我想将 10 个 JPanel 放在一个圆圈中。每个面板的尺寸都相同,两个面板之间的长度应该相同。所以我认为最简单的方法是获取一个空布局并通过 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;
}
但这行不通!有些项目在圆圈上,有些项目像素不对......我完全不知道为什么?! 我也找不到可以为我做这件事的 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();
}
});
}
}
关于java - 在圆中定位组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858337/