I'm trying to layout some JLabels in my application as shown in this example:
I always have this JLabel at the middle and the number of the others JLabels is variable it can go from 1 to 30. I have tried Grid layout by choosing a good number of columns/rows and setting some empty JLabels in the white space but i can't get a good result, and can't find how to do it with MigLayout, did any one have a good layouting soulution or any other solution.
PS: I don't want to show the circle it's just to show that the JLabels are in a arranged in a circle.
Page layout refers to the overall layout and appearance of your document such as how much text you will include on each page, the size of the paper on which you will print your document, and so on.
The definition of a layout is an arrangement, plan or design. An example of a layout is a drawing of how a house will be built. (informal) An establishment or property, especially a large residence or estate. The art or process of arranging printed or graphic matter on a page.
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<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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With