【问题标题】:Fixed size of panel in frame固定框架中面板的大小
【发布时间】:2025-12-28 22:10:11
【问题描述】:

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

【问题讨论】:

  • “请帮我写一些代码”请自行解决问题和任何努力的迹象。 SO 不是代码生成机器。顺便说一句 - 不要对文本使用代码格式,并按照您在预览中的预期检查帖子格式。投票结束。
  • 如果提供一些代码会更好。例如,我会查看您的代码以查看您是否以及在何处调用setPreferredSize
  • 如果面板包含人类可读的文本,不要这样做!字体指标因平台而异。

标签: java swing layout layout-manager


【解决方案1】:

将带有GridLayout 的面板作为单个组件放到GridBagLayout 中,没有约束-它将居中。将带有GBL的面板添加到BorderLayoutCENTER

上图见this example


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

【讨论】:

    【解决方案2】:

    那么你不应该使用 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);
    

    【讨论】:

    • middlePanel.add(innerPanel, constraintsThatPlaceItWhereYouWantIt); 请参阅我的答案,了解为什么 constraintsThatPlaceItWhereYouWantIt 对于在 GBL 中居中​​组件是多余的。它链接到示例代码。
    • 你是对的,但我在添加时仍然总是给出限制,因为可读性。他可能会用它做一些更高级的关于放置的事情。
    • middlePanel.add(innerPanel /* put in center */); ;)
    • 最后一行:yourFrame.add(middlePanel, BorderLayout.CENTER); 怎么样?你也会跳过BorderLayout.CENTER 吗?我不会,虽然它不是必需的。
    【解决方案3】:
        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);
    

    【讨论】:

    • 1) 使用代码格式 2) 这很少,如果有的话,答案。 -1
    • 至少在这种情况下不会有帮助。