Why does the size of the JFrame exceed the size of its ContentPane, even though it has a defined size?

放肆的年华 提交于 2019-11-29 16:14:52
trashgod

You may find it helpful to compare the result from a similar program on a different platform. In particular,

  • The red Border is inside the panel; your usage conforms to the API recommendation, "we recommend that you put the component in a JPanel and set the border on the JPanel."

  • The frame width matches the panel width on Mac OS X because the heavyweight peer used for the top-level container has no vertical border on Mac OS X; the Windows peer has its own border.

  • The frame height includes the drag bar and frame border: 38 pixels on Widows, 22 on Mac OS X.

  • Don't use setPreferredSize() when you really mean to override getPreferredSize().

  • As an aside, the frame's add() method forwards to the content pane.

panel size: [400,300]
frame size: [400,322]

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;

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

public class ExcessiveSpacePanelTest {
    JFrame frame;
    JPanel panel;

    public void initGUI(){
        frame = new JFrame();
        panel = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 300);
            }
        };
        panel.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
        frame.add(panel);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);

        System.out.println("panel size: [" + panel.getSize().width + "," + panel.getSize().height +"]");
        System.out.println("frame size: [" + frame.getSize().width + "," + frame.getSize().height+"]");
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() ->{
            new ExcessiveSpacePanelTest().initGUI();
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!