0

我是 Java 新手(虽然我对 JavaScript 有广泛的了解),但
我正在尝试使用Canvas它,这导致了这个奇怪的问题。在这里
检查代码。如您所见,在我定义了 的大小之后,我正在尝试打印它。 但它不能正确打印尺寸。
Canvas

            setMinimumSize(new Dimension(WIDTH,HEIGHT));
            setMaximumSize(new Dimension(WIDTH,HEIGHT));
            setPreferredSize(new Dimension(WIDTH,HEIGHT));

            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(this, BorderLayout.CENTER);
            frame.pack();
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            System.out.println(getWidth());

为什么尺寸变了?

4

1 回答 1

1

Preferred/min/max sizes are "suggestions" to the layout managers of how your component might like to be laid out, there us no gurenttee that they will used.

A BorderLayout will try and use the available space to fill the component into,

Now, with pack, the frame's size has been set (normally) to the preferred size of the content pane.

So, now your asking, why is it not set to what it supplied. The answer is, the frame also needs to include the frame decoration, which subtracts from the usable space (frame size - decoration insets = available space) , you also need to take into consideration the menu bar

于 2013-01-12T22:46:01.593 回答