8

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

替代文字

我认为正确的对齐是由gapbefore push(如在另一个 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);
    }
}
4

2 回答 2

10

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

    topPanel.setLayout(new MigLayout("", "[][][]push[]", ""));
于 2011-01-14T16:50:03.513 回答
4

一种更简单/更清洁的方式(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");
于 2012-12-17T17:36:33.107 回答