【问题标题】:How to center a component on a row containing multiple components with MiGLayout如何使用 MiGLayout 将组件居中在包含多个组件的行上
【发布时间】:2011-10-21 07:50:14
【问题描述】:

我大约在一个半月前开始使用 MiGLayout,一切都很简单而且效果很好。只有一个问题我仍然无法解决。

假设我想要一个在最右侧有两个按钮和一个居中标题的行,当我这样做时,标题实际上并没有居中:

(“this”是一个JPanel)

this.add(labelTitle, "split, span, center");
this.add(closeButton, "east");
this.add(mainMenuButton, "east");   

发生的情况是“labelTitle”在放置按钮后的剩余空间中居中,但我实际上希望它相对于整个 JPanel 居中,而不仅仅是剩余空间。

我可以使用哪些参数来获得所需的效果?我知道我可以使用绝对定位,但我不想这样做,因为它违背了我首先使用 MiGLayout 的目的。

【问题讨论】:

    标签: java swing miglayout


    【解决方案1】:

    你正在寻找这样的东西吗?

    干杯!

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
    
        JPanel panel = new JPanel(new MigLayout("debug"));
        panel.add(new JLabel("Label Title"), "x2 min(b1.x - unrel, (container.w+pref)/2)");
        panel.add(new JButton("Close Button"), "id b1, pushx, alignx right");
        panel.add(new JButton("Main Menu Button"), "alignx right");
    
        frame.add(panel);
        frame.setSize(800, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    

    【讨论】:

    • 完美运行。不过,我对 MiGLayout 的了解不足以理解所有参数。想解释一下标题标签的工作原理吗?非常感谢您的帮助!
    • 这很容易。它只是为标签的右侧 (x2) 设置一个表达式。在表达式中是左侧按钮的 x,为了能够引用它,我将 ID 设置为 b1。
    【解决方案2】:

    您可以使用 JXLayer 并将按钮放在玻璃窗格中。

    JButton closeButton = new JButton("Close");
    JButton mainMenuButton = new JButton("Menu");
    JLabel labelTitle = new JLabel("Application");
    
    JPanel panel = new JPanel();
    panel.setLayout(new MigLayout(new LC().fillX()));
    panel.add(labelTitle, new CC().alignX("center").spanX());
    
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new MigLayout(new LC().fillX()));
    buttonPanel.add(closeButton, new CC().alignX("right").split());
    buttonPanel.add(mainMenuButton, new CC().alignX("right"));
    buttonPanel.setOpaque(false);
    
    JXLayer<JPanel> mainPanel = new JXLayer<JPanel>();
    mainPanel.setView(panel);
    mainPanel.setGlassPane(buttonPanel);
    
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(mainPanel);
    frame.setSize(400, 600);
    frame.setVisible(true); 
    

    【讨论】:

    • 我很确定它会起作用,但我正在寻找 MiGLayout 的解决方案,无论如何,谢谢!
    【解决方案3】:

    创建 JPanel 时,请使用以下 MigLayout 初始化程序:
    new MigLayout("","[]push[center]push[]","")

    如果您不了解约束,请查看此处:MigLayout Whitepaper

    这是假设您在此 JPanel 中没有任何其他内容...

    【讨论】:

    • 感谢您的尝试,但它不起作用,它仍然位于 REMAINING 空间的中心,而不是面板的中心。
    • 是的,但它不起作用,但我不知道为什么。 @Mikael Grev 给了我一个可行的解决方案,感谢您的尝试!
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2017-06-07
    • 2015-12-10
    • 1970-01-01
    • 2019-06-22
    相关资源
    最近更新 更多