固定面板的尺寸

时间:2012-05-25 06:26:04

标签: java swing layout layout-manager

我已将一些组件添加到设置为网格布局的JPanel,我将其添加到设置为边框布局的JFrame。但我想修复面板的大小。当我的窗口最大化时,所有组件的大小都在增加。即使窗口最大化,我也希望面板位于窗口的中心 固定大小

3 个答案:

答案 0 :(得分:3)

将带有GridLayout的面板作为单个组件放置到GridBagLayout,没有任何约束 - 它将居中。将带有GBL的面板添加到CENTER的{​​{1}}。

有关上图,请参阅this example


Nested Layout Example也使用GBL将图像置于右侧滚动窗格的下半部分。

答案 1 :(得分:1)

那么你不应该使用BorderLayout,因为它只适合子组件。如果你仍然想在JFrame上使用BoderLayout(因为你需要一些侧面板或类似的东西),你可以只包装你的JPanel(使用GridLayout)进入另一个带有GridBagLayout或BoxLayout或类似东西的JPanel,然后将其他JPanel放入JFrame。

JPanel innerPanel = new JPanel();
innerPanel.setLayout(new GridLayout());
// fill and set your innerPanel

JPanel middlePanel = new JPanel();
middlePanel.setLayout(new GridBagLayout());
middlePanel.add(innerPanel, constraintsThatPlaceItWhereYouWantIt);

JFrame yourFrame = new JFrame();
yourFrame.setLayout(new BorderLayout());
yourFrame.add(middlePanel, BorderLayout.CENTER);

答案 2 :(得分:0)

    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new BorderLayout());

    JPanel rootPanel = new JPanel();
    frame.getContentPane().add(rootPanel, BorderLayout.CENTER);
    rootPanel.setLayout(new GridBagLayout());

    JPanel contentPanel = new JPanel();

    Dimension dimension = new Dimension(300, 300);
    contentPanel.setMaximumSize(dimension);
    contentPanel.setMinimumSize(dimension);
    contentPanel.setPreferredSize(dimension);
    contentPanel.setBackground(Color.YELLOW);

    GridBagConstraints g = new GridBagConstraints();
    g.gridx = 0;
    g.gridy = 0;
    g.anchor = GridBagConstraints.CENTER;
    rootPanel.add(contentPanel, g);

    frame.setVisible(true);
相关问题