在 MigLayout 中居中 3 个或更多组件
Centering 3 or more components in MigLayout
我想在我的 GUI 中有同样居中的* 3 个对象,并且我希望有一个简单的解决方案,但我只是找不到正确的方法。
*换句话说:我想让每个组件的中心(和边界)之间的距离相等。
我尝试过的:
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class App {
public static void launchView(){
JFrame frame = new JFrame("Foo");
frame.setLayout(new MigLayout());
JLabel l = new JLabel("Hello");
JButton b = new JButton("Help me");
JLabel l2 = new JLabel("2015-08-06 - 2015-09-32");
frame.add(l, "pos 0.25al 0.5al");
frame.add(b, "pos 0.5al 0.5al");
frame.add(l2, "pos 0.75al 0.5al");
frame.setSize(new Dimension(600, 200));
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
launchView();
}
});
}
}
在图片中你可以看到日期靠近中心,而右侧有很多空闲 space - 它没有居中。 我该如何解决?
您应该定义列约束来存档它。在下面的代码中,我定义了 3 列,它们都平等增长。
对于每一列,我添加一个组件并将其海藻素定义为 x 方向的 50% 和 y 方向的 50%。
您可以通过从布局约束中删除 "debug" 选项来禁用调试模式(单元格周围的虚线边框)。
public class App {
public static void launchView(){
JFrame frame = new JFrame("Foo");
frame.setLayout(new MigLayout("fillx, filly, debug", // Layout Constraints
"[grow][grow][grow]", // Column Constraints
"")); // Row Constraints
JLabel l = new JLabel("Hello");
JButton b = new JButton("Help me");
JLabel l2 = new JLabel("2015-08-06 - 2015-09-32");
frame.add(l, "align 50% 50%");
frame.add(b, "align 50% 50%");
frame.add(l2, "align 50% 50%");
frame.setSize(new Dimension(600, 200));
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
launchView();
}
});
}
}