简体   繁体   中英

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? Could I get the bounds of the BorderLayout instead?

But every argument seems to be 0.

All Swing components have a size of (0, 0) when they are created. 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. Then you can use the getSize() method to control where the painting is done.

You will also need to override the getPreferredSize() method of the panel so the layout manager can pack() the frame properly.

Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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