在MigLayout中居中3个或更多组件

时间:2015-08-06 08:54:11

标签: java swing layout-manager 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();
           }
       });
   }
}

Effect

在图片中您可以看到日期接近中心,而右侧有很多自由空间 - 它不是居中的。 我该如何解决?

1 个答案:

答案 0 :(得分:5)

您应该定义列约束以存档它。在下面的代码中,我定义了3列,它们都平等增长。 对于每一列,我添加一个组件并将其algin定义为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();
           }
       });
   }
}

enter image description here

相关问题