如何围绕 JPanel 缩放 JFrame?

How to scale a JFrame around a JPanel?

我尝试编程 PONG 游戏。

我的问题:我使用 JPanel 作为大小为 (1000;600) 的 "matchfield"。但是,当我使用 setSize(匹配域的维度)将 JPanel 添加到 JFrame 时,右边框和下边框出现问题。 看起来 JFrame 的大小变成了 (1000;600) 而 JPanel 变小了。 我该如何解决?

JPanel 的大小应由其首选大小而非大小决定。最简单的方法是在其上调用 setPreferredSize(...),但这允许其他代码更改其首选大小,因此最安全的方法是覆盖其 public Dimension getPreferredSize() 方法。如果使用 contentPane 将 JPanel 添加到 JFrame 的 BorderLayout,然后在添加 JPanel 之后和显示之前调用 JFrame pack(),JFrame 将自然地正确调整自身大小。

例如:

public class MyJPanel extends JPanel {

    private static final int PREF_W = 1000;
    private static final int PREF_H = 600;

    public MyJPanel() {
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // to make smooth graphics
        Graphics2D g2 = (Graphics2D) g; 
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // do your drawing here
    }

    // size the JPanel correctly
    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("My GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MyJPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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