如何防止 JPanel 继承其容器 JFrame 的大小

How to keep JPanel from inheriting the size of its container JFrame

我创建了一个名为 homeWindowFrame 的 JFrame 并将其大小设置为 (600, 500),然后我向 JFrame 添加了一个名为 mainContainerPanel 的 JPanel。我为 JPanel 设置了一个新的大小,但它不起作用。 JPanel 的大小与 JFrame 的大小保持一致,而不是更新。如何提前在 JFrame.Thanks 中设置 JPanels 的大小。这是我的代码:

/** * 主要 window 建设 */

    JFrame homeWindowFrame = new JFrame("Home - Crime File Management System");

    if (isInvalidLogin) {
        homeWindowFrame.setSize(600, 500);

    } else {
        homeWindowFrame.setSize(600, 400);
    }

    homeWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    homeWindowFrame.setLocation((screenSize.width / 2) - (homeWindowFrame.getWidth() / 2), (screenSize.height / 2) - (homeWindowFrame.getHeight() / 2));


    /**
     * Main panel construction
     */
    JPanel mainContainerPanel;

    if (isInvalidLogin) {
        mainContainerPanel = new JPanel(new GridLayout(4, 2));

    } else {
        mainContainerPanel = new JPanel(new GridLayout(3, 2));
    }

    homeWindowFrame.add(mainContainerPanel);

您的代码似乎忽略了 Java Swing 布局管理器的工作方式。当您将 JPanel 添加到 JFrame 时,默认布局为 BorderLayout,这将使面板在框架中居中并调整其大小以填充框架。如果您希望有一个不同大小的面板,并且需要以某种方式设置其 preferredSize,并且包含 JPanel 的容器将需要使用不同的布局管理器。例如,以 "default" 方式使用的 GridBagLayout(添加一个组件,没有 GridBagConstraints)将使 JPanel 居中,如果这是您想要的。如果这些建议没有帮助,那么你应该创建一个自己的后验MCVE(请阅读link)。

例如,我的 MCVE:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;

@SuppressWarnings("serial")
public class DiffSizedPanel extends JPanel {
    private static final int PANEL_W = 400;
    private static final int PANEL_H = 300;
    private static final int FRAME_W = 600;
    private static final int FRAME_H = 500;
    private static final Color BG_COLOR = Color.PINK;

    public DiffSizedPanel() {
        setBackground(BG_COLOR);

        // set the JPanel the preferred size desired
        setPreferredSize(new Dimension(PANEL_W, PANEL_H));
        setBorder(BorderFactory.createTitledBorder("This is the JPanel"));
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Different Sized Panel");

        // set the JFrame the preferred size desired
        frame.setPreferredSize(new Dimension(FRAME_W, FRAME_H));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // change the content pane's layout from default BorderLayout to GridBagLayout
        frame.getContentPane().setLayout(new GridBagLayout());
        frame.getContentPane().add(new DiffSizedPanel());  // add the JPanel
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}