如何使 JPanel 大小适用于 JFrame?

How to make JPanel size apply to JFrame?

我遇到了 JPanel 的大小没有增加 JFrame 的问题。

这是我的代码:

package pong;

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        
        JPanel p = new JPanel();
        p.setPreferredSize(new Dimension(500, 500));

        frame.add(p);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setVisible(true);
        
        frame.setLocationRelativeTo(null);
    }
}

即使面板的首选尺寸为 500 x 500 像素,框架显示的宽度或高度也很小。

The JFrame is displayed with little width or height at all,

代码应该是:

frame.pack(); // added
frame.setVisible(true);

pack() 方法将调用框架使用的布局管理器,所有 Swing 组件将以其首选大小显示。

此外,作为一般规则,不需要手动设置面板的首选大小,因为您将向面板添加组件,因此首选大小应基于您添加到面板的组件.

阅读 Using Layout Managers 上的 Swing 教程部分以获取更多信息和示例。