Java get component dimension in constructor

213 views Asked by At

I have a Panel which needs to know its size inside the constructor:

class Panneau extends JPanel {
    public Panneau() {
        super();
        new Map(getSize());
    }
}

Unfortunately, the size doesn’t seem to have been initialized yet and getSize() returns a Dimension with 0 for height and width. How to get the future Dimension notwithstanding?

1

There are 1 answers

0
Wouter Lievens On BEST ANSWER

If you want to work with the size of a component, you need to do so when the component is actually in use in a well-formed user interface.

One of the ways to do that, is to add a ComponentListener to the code and implement the componentResized method, which will be called whenever the component's size changes. There you can work with the latest accurate value for the component's size by using getSize().