2

我有一个MyPanel扩展类JPanel
MyPanel是一个子面板:他的大小是由LayoutManager他的父母计算的。
问题是,MyPanel一旦LayoutManager他的父母计算出他的大小,我就需要得到通知。
需要通知它,因为我需要根据面板的大小初始化一些变量。

如果我调用getSize()MyPanel 构造函数,我会得到 (0,0),因为面板还没有“准备好”。
我应该什么时候打电话getSize()

我想要这样的东西:

/** 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
}

有没有类似的东西?也许doLayout()

我能找到的唯一方法是调用getSize()paintComponent()方法......它肯定有效,因为面板在paintComponent()被调用时肯定会显示,但我不能这样做,因为我需要在知道面板大小后立即初始化一些变量.. .但只有一次!paintComponent()会被多次调用...

4

2 回答 2

4

最好的方法是使用 ComponentListener。

参见 ComponentListener.componentResized(ComponentEvent)

于 2012-05-04T19:03:12.373 回答
4

ComponentListener.componentResized()

于 2012-05-04T19:03:20.080 回答