此示例演示如何放置总共3个按钮,其中第一行中包含2个按钮。然后发生换行,因此最后一个按钮在新行中。
约束是简单的字符串,在这种情况下,放置组件时会“换行”。
public class ShowMigLayout { // 创建元素 private final JFrame demo = new JFrame(); private final JPanel panel = new JPanel(); private final JButton button1 = new JButton("First Button"); private final JButton button2 = new JButton("Second Button"); private final JButton button3 = new JButton("Third Button"); public static void main(String[] args) { ShowMigLayout showMigLayout = new ShowMigLayout(); SwingUtilities.invokeLater(showMigLayout::createAndShowGui); } public void createAndShowGui() { // 设置框架的位置和尺寸 demo.setBounds(400, 400, 250, 120); // 告诉面板将MigLayout用作布局管理器 panel.setLayout(new MigLayout()); panel.add(button1); // 注意包装 panel.add(button2, "wrap"); panel.add(button3); demo.add(panel); demo.setVisible(true); } }
输出: