【问题标题】:miglayout: can't get right-alignment to workmiglayout:无法右对齐工作
【发布时间】:2011-06-09 06:36:20
【问题描述】:

这里有点不对劲。我试图让最右边的按钮(在下面的示例中标记为“帮助”)与 JFrame 右对齐,并将巨大的按钮的宽度与 JFrame 绑定,但每个按钮至少为 180px。我得到了巨大的按钮约束,但不是正确的对齐方式。

我认为正确的对齐是由gapbefore push(如this other SO question)完成的,但我想不通。

谁能帮帮我?

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;

public class RightAlignQuestion {
    public static void main(String[] args) {
        JFrame frame = new JFrame("right align question");
        JPanel mainPanel = new JPanel();
        frame.setContentPane(mainPanel);

        mainPanel.setLayout(new MigLayout("insets 0", "[grow]", ""));

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new MigLayout("", "[][][][]", ""));
        for (int i = 0; i < 3; ++i)
            topPanel.add(new JButton("button"+i), "");
        topPanel.add(new JButton("help"), "gapbefore push, wrap");
        topPanel.add(new JButton("big button"), "span 3, grow");

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new MigLayout("",
              "[180:180:,grow][180:180:,grow]","100:"));
        bottomPanel.add(new JButton("tweedledee"), "grow");
        bottomPanel.add(new JButton("tweedledum"), "grow");

        mainPanel.add(topPanel, "grow, wrap");
        mainPanel.add(bottomPanel, "grow");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

【问题讨论】:

  • 我对 MigLayout 的了解还不够,无法回答这个问题,但请尝试在 topPanel 上放置边框以确保它实际上与窗口一样宽。如果不是,那就可以解释为什么帮助不是右对齐的。

标签: swing miglayout


【解决方案1】:

没关系,我明白了:看起来在列规范中需要有一个间隙约束,而不是在组件级别:

    topPanel.setLayout(new MigLayout("", "[][][]push[]", ""));

【讨论】:

  • 我在自己的应用程序中使用“span, gapleft push”完成此操作
  • panel.add(button, "cell 2 0, gapleft push"); 对我有用。请记住,这仅在您添加组件时完成。
【解决方案2】:

一种更简单/更清洁的方式 (IMOH) 是使用组件约束并做

topPanel.add(new JButton("help"), "push, al right, wrap");

Push 将在窗口拉伸时将单元格推出,但您需要告诉组件将自身绑定到单元格的右侧。您可以使用以下代码实现上述目标。

    JPanel topPanel = new JPanel();
    frame.setContentPane(topPanel);

    for (int i = 0; i < 3; ++i)
        topPanel.add(new JButton("button"+i), "");
    topPanel.add(new JButton("help"), "push, al right, wrap");


    topPanel.add(new JButton("big button"), "span 3, grow, wrap");

    topPanel.add(new JButton("tweedledee"), "span, split2,grow, w 180, h 100");
    topPanel.add(new JButton("tweedledum"), "w 180, h 100, grow");

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2014-02-19
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多