I\'m trying to layout some JLabels in my application as shown in this example:
You don't need a layout manager which specifically supports this. You can calculate the x, y positions yourself with some fairly simple trigonometry, then use a regular layout such as 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 points = new ArrayList();
points.add(centre);
//Add points
for (int i=0; i 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);
}
}
