简体   繁体   中英

Get height and width of JComponent in constructor

I want to get the height and width of my JFrame so that a graphic should be at the same relative position even if the window is resized. To do this, I am trying to get the height and width in my constructor, but it always returns 0. What is the best way to do this?

public class FireworkComponent extends JComponent {
   public FireworkComponent() {
   //some variables ....

  this.getHeight();
  this.getWidth();
    }

}

The dimensions will return 0 if the component isn't realized (ie visible). If you override the component's paintComponent method, you will be able to retrieve the container's dimensions and set a graphic at a specific location by drawing on the component's Graphics object.

Try calling pack(); before calling getHeight(); or getWidth();

Don't try to get it in the constructor use this.HEIGHT and this.WIDTH and set it with

public void setLocation(int x, int y) method. Make sure you do this in the paintcomponent method you should be overriding so it called it every time it is re-sized.

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