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

时间:2017-09-03 15:39:54

标签: java swing layout jframe jpanel

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

/ **          *主窗口结构          * /

    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);

1 个答案:

答案 0 :(得分:1)

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

例如, MY 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());
    }
}