Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

(Swing) getTopLevelAncestor just returns null

843807May 19 2010 — edited May 19 2010
I can't seem to get this one right. According to the docs, getTopLevelAncestor() returns:

"Returns the top-level ancestor of this component (either the containing Window or Applet), or null if this component has not been added to any container. "

Seems simple enough, but I can't get it to return anything but null.

Here's some sample code - first a top level container JFrame:
import java.awt.*;
import javax.swing.*;

public class Top extends JFrame {
	
	private MyPanel mp;
	
	public Top() {
		super("Test Frame");
		
		mp = new MyPanel();
		getContentPane().add(mp);
		pack();
		setVisible(true);
	}

	public static void main(String[] args) {
		new Top();
	}	
}
And then a nice panel to fill it:
import java.awt.*;
import javax.swing.*;

public class MyPanel extends JPanel {
	
	private JLabel label;
	
	public MyPanel() {
		super(new FlowLayout());
		Container topF = this.getTopLevelAncestor();
		label = new JLabel();
		add(label);
		if (topF == null) {
			label.setText("Only got null");
		} else {
			label.setText("Actually got a container ref");
		}
	}
}
Alas, it keeps throwing me nulls. What am I doing wrong?

TIA,
GMA
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 16 2010
Added on May 19 2010
3 comments
980 views