布局管理器可以制作镶板GUI吗?

时间:2015-09-01 02:39:55

标签: java swing layout-manager

我希望像这样申请:

------------------------------
|         Toolbar            |
------------------------------
|              |             |
|              |             |
|              |-------------|
|              |             |
|              |             |
------------------------------

哪种布局管理器适合用于屏幕链接?

1 个答案:

答案 0 :(得分:4)

我建议GroupLayout。一旦习惯了它,没有任何东西可以为你调整GroupLayout组件的大小。你可以使用这样的东西:

import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.BevelBorder;

public class LayoutFrame extends JFrame {
  private JPanel contentPane;
  private JMenuBar menuBar;

  public LayoutFrame() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Create the toolbar
    menuBar = new JMenuBar();
    menuBar.add(new JMenu("File"));
    setJMenuBar(menuBar);

    setSize(500, 500);

    contentPane = new JPanel();
    GroupLayout layout = new GroupLayout(contentPane);
    contentPane.setLayout(layout);
    setContentPane(contentPane);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    // Create the panels for the different regions
    JPanel leftPanel = new JPanel();
    leftPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    JPanel topRightPanel = new JPanel();
    topRightPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    JPanel bottomRightPanel = new JPanel();
    bottomRightPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));

    // Create a sequential group for the horizontal axis.
    GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
    hGroup.addComponent(leftPanel);
    hGroup.addGroup(layout.createParallelGroup().
             addComponent(topRightPanel).addComponent(bottomRightPanel));
    layout.setHorizontalGroup(hGroup);

    // Create a parallel group for the vertical axis.
    GroupLayout.ParallelGroup vGroup = layout.createParallelGroup();
    vGroup.addComponent(leftPanel);
    vGroup.addGroup(layout.createSequentialGroup().
             addComponent(topRightPanel).addComponent(bottomRightPanel));
    layout.setVerticalGroup(vGroup);
  }

  public static void main(String[] args) {
    final LayoutFrame frame = new LayoutFrame();
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        frame.setVisible(true);
      }
    });
  }
}

这会创建此框架(Ubuntu Unity)。你应该能够弄清楚如何自己调整差距。

Screenshot No Gaps

并且有自动差距:

Screenshot With Gaps