Get height and width of JComponent in constructor

I want to get the height and width of my JFrame so that the graphic is in the same relative position, even if the window size has changed. To do this, I try 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(); } 

}

+4
source share
3 answers

Dimensions return 0 if the component is not implemented (i.e. visible). If you override the method of the paintComponent component, you can get the dimensions of the container and set the graphics in a specific place by drawing a Graphics object.

+4
source

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

+2
source

Do not 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, which you must override, so it calls it every time it is changed.

+2
source

Source: https://habr.com/ru/post/1380441/


All Articles