简体   繁体   English

如何获得以另一个JPanel为中心的JPanel的边界?

[英]How do I get the bounds of a JPanel centered in another JPanel?

I have a main panel with a border layout containing another panel in the center. 我有一个带有边框布局的主面板,中间包含另一个面板。 Because I want to paint inside the centered panel I have to get the bounds of it. 因为我想在居中的面板内绘画,所以必须确定其边界。

panel_main.add(panel, BorderLayout.CENTER);

I wanted to save the bounds in a rectangle like this: 我想将边界保存在这样的矩形中:

Rectangle bounding = new Rectangle 
   (panel.getX(), panel.getY(), panel.getWidth(), panel.getHeight());

But every argument seems to be 0. So how do I get the bounds of the panel? 但是每个参数似乎都是0。那么,如何确定面板的边界呢? Could I get the bounds of the BorderLayout instead? 我可以代替BorderLayout的边界吗?

But every argument seems to be 0. 但是每个参数似乎都是0。

All Swing components have a size of (0, 0) when they are created. 创建时,所有Swing组件的大小均为(0,0)。 Components are only given a size when the frame is packed and made visible. 仅当包装好框架并使其可见时,才为组件指定尺寸。

Because I want to paint inside the centered panel I have to get the bounds of it. 因为我想在居中的面板内绘画,所以必须确定其边界。

You override the paintComponent() method of the panel. 您覆盖面板的paintComponent()方法。 Then you can use the getSize() method to control where the painting is done. 然后,您可以使用getSize()方法来控制绘画的位置。

You will also need to override the getPreferredSize() method of the panel so the layout manager can pack() the frame properly. 您还需要覆盖面板的getPreferredSize()方法,以便布局管理器可以正确包装()框架。

Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started. 阅读Swing教程“ 自定义绘画”中的这一部分,以获取更多信息和工作示例,以开始使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM