Question

Alright so I was watching a tutorial on Java game development and he used some code I am unsure of what it does. I would like to know because the game won't run without it. I am trying to learn as much on this subject as I can and would like to know what it does. The code is below thank you for all your help.

public void addNotify() {
    super.addNotify();
    if(thread == null) {
        thread = new Thread(this);
        addKeyListener(this);
        thread.start();
    }
}

No correct solution

OTHER TIPS

From the JavaDocs for Container

Makes this Container displayable by connecting it to a native screen resource. Making a container displayable will cause all of its children to be made displayable. This method is called internally by the toolkit and should not be called directly by programs.

From the JavaDocs for JComponent

Notifies this component that it now has a parent component. When this method is invoked, the chain of parent components is set up with KeyboardAction event listeners. This method is called by the toolkit internally and should not be called directly by programs.

Okay, but what does that all mean?

Basically, addNotify in Container sets up the event dispatchers/monitors used internally by the components to track and handle events. It will also call addNotify to all the child components it containers.

addNotify in JComponent fires a ancestor property change event and sets up the focus transversal and key bindings for the component.

These methods are called by Container#addImpl when a component is added to a displayable container (one that is attached to a native peer). This provides them with notification that the component has been added, specifically, to a native peer.

This is a good way to know that you component is been added to a displayable context and will soon be laid out and painted.

Equally, there is also a removeNotify for when a component is removed or it's parent container is removed from a displayable context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top