-
super.addNotify()
I'm reading Killer Game Programming in Java, however I'm confused about something, and that is how addNotify works exactly.
In an effort to understand, I did this:
Code:
public class GamePanel extends JPanel implements Runnable
{
// some variables .......
public GamePanel()
{
System.out.println("Constructor started");
setBackground(Color.white);
setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
// create game components
// ..
System.out.println("Constructor ended");
} // END OF GAMEPANEL
@Override
public void addNotify()
{
System.out.println("addNotify started");
super.addNotify();
startGame();
System.out.println("addNotify ended");
}
// some more stuff, not relevant
}
The JFrame:
Code:
public class Main extends JFrame
{
public Main()
{
System.out.println("Constructor main started");
setTitle("game");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new GamePanel());
try
{
Thread.sleep(3000);
System.out.println("setVisible getting called");
} catch (InterruptedException e)
{
e.printStackTrace();
}
setVisible(true);
try
{
System.out.println("setVisible ended");
Thread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Constructor main ended");
}
public static void main(String[] args) {
new Main();
}
}
The result was this:
Constructor main started
Constructor started
Constructor ended
(*Imagine a 3 second delay here*)
setVisible getting called
addNotify started
addNotify ended
setVisible ended
(*Imagine another 3 second delay*)
Constructor main ended
So it is clear addNotify gets called only when setVisible() of the JFrame is called, and that is desired I suppose. But why? GamePanel isn't an subclass of Main, is it? Maybe I'm just tired, but I dont get how this works exactly
-
Re: super.addNotify()
GamePanel is a subclass of JPanel. The JPanel is added to the JFrame, so the JPanel becomes visible when the JFrame becomes visible.