Reputation: 4378
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
Reputation: 35011
Best way is to use a ComponentListener.
See ComponentListener.componentResized(ComponentEvent)
Upvotes: 4