哪种布局可以做到这一点? [英] Which layout can do this?
问题描述
我正在尝试在我的应用程序中布局一些JLabel,如下例所示:
I'm trying to layout some JLabels in my application as shown in this example:
我总是把这个JLabel放在中间,其他JLabel的数量是可变的,它可以去从1到30.我通过选择大量的列/行并在空白区域设置一些空的JLabel来尝试网格布局,但是我无法获得良好的结果,并且无法找到如何使用 MigLayout ,是否有任何人有一个良好的布局解决方案或任何其他解决方案。
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 :我不想显示圆圈,只是为了表明JLabel排成一个圆圈。
PS: I don't want to show the circle it's just to show that the JLabels are in a arranged in a circle.
推荐答案
您不需要专门支持此功能的布局管理器。您可以使用一些相当简单的三角函数计算x,y位置,然后使用常规布局,例如 SpringLayout
。
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);
}
}
这篇关于哪种布局可以做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!