Oneiros
Oneiros

Reputation: 4378

JPanel notified by LayoutManager when resized

I have a class MyPanel that extends JPanel.
MyPanel is a child panel: his size is dinamically calculated by the LayoutManager of his parent.
The problem is that I need MyPanel to be notified as soon as the LayoutManager of his parent calculates his size.
It needs to be notified because I need to initialize some variables according to the panel's size.

If I call getSize() in the MyPanel constructor i get (0,0) because the panel is not "ready".
When should i call getSize()?

I'd like to have something like this:

/** Lays out the panel and sets his size according to his layout */
@Override
public void onReady() {
    System.out.println(getSize()); //output is (0,0);
    super.onReady();
    System.out.println(getSize()); //output is (600,500);
    //here i can initialize my variables
}

Is there something similar? Maybe doLayout()?

The only way i could find is calling getSize() in the paintComponent() method... it surely works because the panel is surely displayed when paintComponent() is called but I can't do this because i need to initialize some variables as soon as i know the panel size... but only once! paintComponent() will be called several times...

Upvotes: 2

Views: 220

Answers (2)

Moritz Petersen
Moritz Petersen

Reputation: 13057

It's ComponentListener.componentResized().

Upvotes: 4

ControlAltDel
ControlAltDel

Reputation: 35011

Best way is to use a ComponentListener.

See ComponentListener.componentResized(ComponentEvent)

Upvotes: 4

Related Questions