Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }

}

like image 210
trs Avatar asked Feb 23 '23 11:02

trs


1 Answers

The dimensions will return 0 if the component isn't realized (i.e. 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.

like image 169
mre Avatar answered Mar 05 '23 10:03

mre