您不需要专门支持此功能的布局管理器。您可以使用一些相当简单的三角函数来计算x,y位置,然后使用常规布局,例如.SpringLayout
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class CircleLayout {
/**
* Calculate x,y positions of n labels positioned in
* a circle around a central point. Assumes AWT coordinate
* system where origin (0,0) is top left.
* @param args
*/
public static void main(String[] args) {
int n = 6; //Number of labels
int radius = 100;
Point centre = new Point(200,200);
double angle = Math.toRadians(360/n);
List<Point> points = new ArrayList<Point>();
points.add(centre);
//Add points
for (int i=0; i<n; i++) {
double theta = i*angle;
int dx = (int)(radius * Math.sin(theta));
int dy = (int)(-radius * Math.cos(theta));
Point p = new Point(centre.x + dx, centre.y + dy);
points.add(p);
}
draw(points);
}
private static void draw(List<Point> points) {
JFrame frame = new JFrame("Labels in a circle");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();;
SpringLayout layout = new SpringLayout();
int count = 0;
for (Point point : points) {
JLabel label = new JLabel("Point " + count);
panel.add(label);
count++;
layout.putConstraint(SpringLayout.WEST, label, point.x, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, label, point.y, SpringLayout.NORTH, panel);
}
panel.setLayout(layout);
frame.add(panel);
frame.setVisible(true);
}
}