如何在 JFrame 中设置 JPanel 的大小?

How to set a size for a JPanel inside a JFrame?

我试图将一个 JPanel 放在全屏 JFrame 的中心,并具有定义的大小,但它总是在整个屏幕上伸展...

我尝试了 setBoundssetPreferredSize,但它们不起作用。

这是代码:

public static void showScene(){
//Create the frame to main application.
    JFrame frame = new JFrame("Application"); // set the title of the frame
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);  // set the size, maximum size.
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create the panel to store the main menu.
    JPanel panel = new JPanel();

    panel.setPreferredSize(new Dimension(500,200));
    panel.setBackground(new java.awt.Color(0,0,255));

    frame.add(panel,BorderLayout.CENTER);

}

public static void main (String[] args){

    showScene();

}

BorderLayout 拉伸内容以填充父容器。

如果您希望子项的尺寸小于父项,请使用其他一些 LayoutManager(尝试 FlowLayout)。


您可以使用以下代码更改布局。

Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 0,90)));

frame.add(panel);

frame.pack();

如需进一步参考,请遵循 visual guide to layout managers

祝你好运。