Why is Greenland a part of Denmark?

Though a part of the North American continent, Greenland has been associated first with Norway, then Denmark since the 9th Century.  Its head of state is King Frederik X of Denmark.  It is an autonomous Danish territory with self-government and its own parliament.  But how did this all come about?